define(function(require) {
	'use strict';
	//自定义共通方法
	var libs = angular.module('starter.libs', []);

	//用户信息
	var AUTH_KEY = [
		'user_id', //用户登录之后的session
		'user_name', //用户账户名
		'user_nick', //用户昵称
		'user_type', //用户身份 1：终端用户    2：店家
		'user_avatar', //用户头像
		'issue_type', //用户当前使用身份 1买家 2卖家
		'store_id', //用户所属门店ID
		'store_issue', // 店铺类型	1:制造商，2:品牌代理商，3:代理商/分仓	4:经销商
		'store_issue_name', //店铺类型名称
		'is_warehouse', // 是否分仓 true	分仓
		'store_approved', // 0:审核中，1:审核通过，2:审核未通过
		'member_id', //会员id
		'store_qr', // 店铺二维码
		'token', //令牌
		'verify_email',//是否验证过邮箱
	];

	//http请求
	libs.service('Http', function($http, $ionicLoading, $timeout, $cacheFactory) {
		//定位例外接口
		var LOCALTION = [
			"goods.main.search",
			"map.memdistribution.search",
			"member.login",
			"member.thirdpartlogin",
			"member.getCellphoneCodeNew"
		];
		//签名处理
		function sign(args) {
			//1.根据参数名称（系统参数和应用参数）将所要传递的参数（签名除外）按照参数名做升序排序，然后对参数名和参数值（使用UTF-8编码）链接成字符串。
			delete args.sign; //签名除外

			var keys = Object.keys(args);
			keys = keys.sort();
			var result = '';
			for(var k in args) {
				result = result + k + '=' + args[k] + '&';
			}
			//2.将此字符串加上中心会话密钥token进行一次MD5，获得十六进制字符串，转成大写格式。
			result = result + HTTP_TOKEN;
			result = hex_md5(result).toUpperCase();
			//3.将一次MD5后的字符串再次MD5，获得十六进制字符串，转成大写格式。
			result = hex_md5(result).toUpperCase();
			//4.最后把结果当做一个请求参数，名称为sign。
			return result;
		};
		//获取session值其实就是user_id
		function get_session() {
			var sessionValue = localStorage.getItem('user_id');
			return sessionValue == undefined ? '' : sessionValue;
		}
		//保存session值其实就是user_id
		function save_session(session) {
			localStorage.setItem('user_id', session);
		}
		//获取session值其实就是user_id
		function get_session_localtion() {
			var sessionValue = localStorage.getItem('session');
			return sessionValue == undefined ? '' : sessionValue;
		}
		//清除session
		function clear_loginInfo_local() {
			for(var i = 0; i < AUTH_KEY.length; i++) {
				localStorage.removeItem(AUTH_KEY[i]);
			}
		}
		//消息提示
		function toast(message) {
			//创建toast对象
			var toastDiv = document.createElement('div');
			toastDiv.innerHTML = message;
			toastDiv.setAttribute("class", "toast");
			document.body.appendChild(toastDiv);
			//设置消失时间
			setTimeout(function() {
				var d = 0.5;
				toastDiv.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
				toastDiv.style.opacity = '0';
				$timeout(function() {
					document.body.removeChild(toastDiv)
				}, d * 1000);
			}, 2000);
		}
		//显示lodding
		function httpConnect(method, args, isShow, success, error, done) {

			if(!method) method = 'POST';

			//定位例外
			var islocaltion = false;
			for(var i = 0; i < LOCALTION.length; i++) {
				if(LOCALTION[i] == args.method)
					islocaltion = true;
			}
			//假如是定位例外
			if(islocaltion) {
				//判断是否存在
				if(args.session == undefined || args.session == '')
					args.session = get_session();
				//判断是否存在
				if(args.session == undefined || args.session == '')
					args.session = get_session_localtion();
			} else {
				//判断是否存在
				if(args.session == undefined)
					args.session = get_session();
			}

			//提交数据
			var post_data = {
				sign: sign(args),
				method: args.method,
				api_version: '1.0'
			};

			for(var k in args) {
				post_data[k] = args[k]
			}

			var getparam = '';
			if(method == 'GET' || method == 'DELETE') {
				for(var k in post_data) {
					if(!getparam) {
						getparam += '?';
					} else {
						getparam += '&';
					}
					getparam += k + '=' + encodeURIComponent(post_data[k]);
				}
			}

			//			console.log(post_data)
			//跨域请求数据
			httpGoData({
				getparam: getparam,
				method: method,
				post_data: post_data,
				isShow: isShow
			}, success, error, done, function() {
				$timeout(function() {
					delete args.session;
					httpConnect(method, args, isShow, success, error, done);
				}, 300);
			});
		}

		function httpGoData(params, success, error, done, restart) {
			$http({
				url: HTTP_URL + params.getparam,
				method: params.method,
				data: (params.method == 'GET' || params.method == 'DELETE') ? undefined : params.post_data,
				isShow: params.isShow
			}).success(function(data) {
				if(data) {
					if(data.success == -1) {
						//自动登录执行 member.auto_login
						httprelogin(function() {
							//再次请求
							if(restart)
								restart();
						}, function() {
							//清除session
							clear_loginInfo_local();
							if(restart)
								restart();
						});
					} else {
						if(success)
							success(data);
					}
				}
			}).error(function(e) {
				if(error)
					error(e);
			}).finally(function() {
				if(done)
					done();
			});
		}

		function httpConnectUrl(url, method, success, error, done) {
			//跨域请求数据
			$http({
				url: url,
				method: method,
				data: (method == 'GET' || method == 'DELETE') ? undefined : post_data,
			}).success(function(data) {
				if(success)
					success(data);
			}).error(function(e) {
				if(error)
					error(e);
			}).finally(function() {
				if(done)
					done();
			});
		}

		function httprelogin(success, error) {
			//参数
			var args = {
				uname: localStorage.getItem("user_name"),
				token: localStorage.getItem("token"),
				source: ionic.Platform.isIOS() ? "ios" : "android",
				province_name: localStorage.getItem("province_name"),
				city_name: localStorage.getItem("city_name"),
				district_name: localStorage.getItem("district_name"),
			};
			//提交数据
			var post_data = {
				sign: sign(args),
				method: 'member.auto_login',
				api_version: '1.0'
			};
			for(var k in args) {
				post_data[k] = args[k]
			}
			//跨域请求数据
			$http({
				url: HTTP_URL,
				method: 'POST',
				data: post_data,
			}).success(function(res) {
				if(res.result != undefined) {
					//更新session
					save_session(res.result['session']);
					//继续处理
					if(success)
						success();
				} else {
					if(error)
						error();
				}
			}).error(function(e) {
				if(error)
					error();
			}).finally(function() {
				if(done)
					done();
			});
		}

		return {
			httprelogin: httprelogin,
			sign: sign,
			//显示加载等待
			post: function(args, success, error, done) {
				httpConnect('POST', args, true, success, error, done);
			},
			//隐藏加载等待
			postHide: function(args, success, error, done) {
				httpConnect('POST', args, false, success, error, done);
			},
			get: function(args, success, error, done) {
				httpConnect('GET', args, false, success, error, done);
			},
			getUrl: function(url, success, error, done) {
				httpConnectUrl(url, 'GET', false, success, error, done);
			},
			savecitys: function(province_name, city_name, district_name) {
				localStorage.setItem('province_name', province_name);
				localStorage.setItem('city_name', city_name);
				localStorage.setItem('district_name', district_name);
			},
		};
	})

	//用户信息
	libs.service("Auth", function($rootScope, Http) {

		function refresh_Auth_Remote(cb, error, done) {
			var Infos = get_loginInfo_local();
			if(!Infos) {
				done && done();
				return;
			}

			var param = {
				method: 'member.get',
				'session': Infos.user_id
			}

			//post请求
			Http.post(param, function(res) {
				if(res.success == true) {
					var info = res.result;
					for(var k in info) {
						if(info[k] == null || info[k] == undefined) {
							info[k] = '';
						}
					}
					//更新用户信息
					info.autologin_token_ios = ionic.Platform.isIOS() ? localStorage.getItem("token") : "";
					info.autologin_token_android = ionic.Platform.isIOS() ? "" : localStorage.getItem("token");
					save_loginInfo_local(info);
				}

				cb && cb(res.success == true)
			}, error, done)
		}

		function get_loginInfo_local() {
			var Info = new Object();
			for(var i = 0; i < AUTH_KEY.length; i++) {
				Info[AUTH_KEY[i]] = localStorage.getItem(AUTH_KEY[i]);
			}
			return Info;
		}

		function clear_loginInfo_local() {
			for(var i = 0; i < AUTH_KEY.length; i++) {
				localStorage.removeItem(AUTH_KEY[i]);
			}
			get_issue_type_class_pop();
		}

		function save_loginInfo_local(info) {
			var params = new Object();
			params.user_id = info.session || '';
			params.user_name = info.name || '';
			params.user_nick = info.nickname || '';
			params.user_avatar = info.avatar || '';
			params.user_type = info.seller == 'seller' ? 2 : 1;
			params.issue_type = info.store_id != '' ? 2 : (info.issue_type || 1); //优先显示卖家。info.issue_type || 1
			params.store_id = info.store_id || '';
			params.store_issue = info.issue_type || '';
			params.store_issue_name = info.issue_name || '';
			params.is_warehouse = (info.issue_type == 3) ? ((info.is_warehouse == 'Y') ? true : false) : '';
			params.store_approved = info.approved || '';
			params.member_id = info.member_id || '';
			params.store_qr = info.store_qr || '';
			params.verify_email = info.verify_email || '';//是否验证过邮箱
			params.token = ionic.Platform.isIOS() ? info.autologin_token_ios : info.autologin_token_android;
			for(var i = 0; i < AUTH_KEY.length; i++) {
				localStorage.setItem(AUTH_KEY[i], params[AUTH_KEY[i]]);
			}
			get_issue_type_class_pop();
		}

		function save_loginInfo_change(params) {
			for(var i = 0; i < AUTH_KEY.length; i++) {
				localStorage.setItem(AUTH_KEY[i], params[AUTH_KEY[i]]);
			}
			get_issue_type_class_pop();
		}

		function save_loginInfo_local_singleitem(key, val) {
			for(var i = 0; i < AUTH_KEY.length; i++) {
				if(AUTH_KEY[i] === key) {
					localStorage.setItem(key, val);
					break;
				}
			}
		}

		function save_session(session) {
			localStorage.setItem("session", session);
		}

		function get_session() {
			return localStorage.getItem("session");
		}

		//检查用户身份
		function user_type() {
			var infos = get_loginInfo_local();
			//属于卖家
			if(infos.user_type == 2) {
				// 店铺类型	1:开发商，2:品牌代理商，3:代理商/分仓	4:经销商
				if(infos.store_issue == 1) {
					return 1;
				} else if(infos.store_issue == 2) {
					return 2;
				} else if(infos.store_issue == 3) {
					return 3;
				} else if(infos.store_issue == 4) {
					return 4;
				} else {
					return 5;
				}
			} else {
				return 5;
			}
		}

		//读取当前用户的权限
		function get_user_auth_http(callback) {
			//获取所有权限
			Http.postHide({
				method: 'member.assistente.rightlist'
			}, function(res) {
				//保存当前用户权限
				$rootScope.wlwj_user_auth = res.result;
				if(callback)
					callback(res.result);
//					console.log(res)
			})
		}
		//颜色变更
		function get_issue_type_class_pop() {
			var infos = get_loginInfo_local();
			if(infos.issue_type != 1 && infos.issue_type != undefined) {
				$rootScope.baseclass = 'shop';
				$rootScope.tabcartname = '购物车';
			} else {
				$rootScope.baseclass = 'customer';
				$rootScope.tabcartname = '采购车';
			}
			//是否登录
			//			if(infos.user_id == undefined) {
			//				$rootScope.isLoginTabs = false;
			//			} else {
			//				$rootScope.isLoginTabs = true;
			//			}
		}

		//记录登录用户
		function savekeyremember(username) {
			localStorage.setItem("KEY_REMEMBERME", 'true');
			localStorage.setItem("KEY_REMEMBERME_ID", username);
		}

		//删除登录用户
		function removekeyremember() {
			localStorage.removeItem("KEY_REMEMBERME");
			localStorage.removeItem("KEY_REMEMBERME_ID");
		}

		function getkeyremember() {
			var status = localStorage.getItem("KEY_REMEMBERME");
			if(status) {
				return localStorage.getItem("KEY_REMEMBERME_ID");
			} else {
				return "";
			}
		}

		//删除登录用户
		function saveisrestart() {
			localStorage.setItem('isstart', 1);
		}

		function getisrestart() {
			localStorage.getItem('isstart');
		}

		return {
			getisrestart: function() {
				return getisrestart();
			},
			saverestart: function() {
				saveisrestart();
			},
			getremember: function() {
				return getkeyremember();
			},
			saveremember: function(username) {
				savekeyremember(username);
			},
			removeremember: function() {
				removekeyremember();
			},
			get_user_id: function() {
				var infos = get_loginInfo_local();
				return infos.user_id == undefined ? '' : infos.user_id;
			},
			get_store_id: function() {
				var infos = get_loginInfo_local();
				return infos.store_id == undefined ? '' : infos.store_id;
			},
			check_loginInfo: function() {
				var infos = get_loginInfo_local();
				if(!infos.user_id) {
					return false;
				} else {
					return true;
				}
			},
			get_loginInfo: function() {
				var infos = get_loginInfo_local();
				return infos;
			},
			refresh_loginInfo: function(cb, error, done) {
				refresh_Auth_Remote(cb, error, done);
			},

			clear_loginInfo: function() {
				return clear_loginInfo_local();
			},
			save_loginInfo: function(params) {
				return save_loginInfo_local(params);
			},
			check_user_type: function() {
				return user_type();
			},
			check_issue_type: function() {
				var infos = get_loginInfo_local();
				return infos.issue_type == undefined ? '1' : infos.issue_type;
			},
			save_loginInfo_item: function(k, v) {
				return save_loginInfo_local_singleitem(k, v);
			},
			save_loginInfo_change: function(params) {
				return save_loginInfo_change(params);
			},
			get_memberId: function() {
				var infos = get_loginInfo_local();
				return infos.member_id == undefined ? '' : infos.member_id;
			},
			save_session: function(session) {
				save_session(session);
			},
			get_session: function() {
				return get_session();
			},
			//权限控制
			get_check_user_auth: function(name, callback) {
				//				console.log('传入========'+name)
				var isHave = false;
				if($rootScope.wlwj_user_auth == undefined || $rootScope.wlwj_user_auth == '') { //如果全局变量里没有，则再次请求权限接口
					get_user_auth_http(function(rights) {
						if(rights) {
							for(var i = 0; i < rights.length; i++) {
								if(rights[i].right_name == name) {
									isHave = true;
									break;
								}
							}
						}
						if(callback)
							callback(isHave);
					});
				} else {
					for(var i = 0; i < $rootScope.wlwj_user_auth.length; i++) {
						if($rootScope.wlwj_user_auth[i].right_name == name) {
							isHave = true;
							break;
						}
					}
					if(callback)
						callback(isHave);
				}
			},
			//我的未来万家 权限控制
			get_check_user_auth_menu: function(name, callback) {
				var isHave = false;
				if(name.indexOf('all') > 0) { //all表示不控制
					isHave = true;
				} else {
					if($rootScope.wlwj_user_auth == undefined || $rootScope.wlwj_user_auth == "") { //如果全局变量里没有，则再次请求权限接口
						get_user_auth_http(function(rights) {
							if(!rights) return;
							for(var i = 0; i < rights.length; i++) {
								if(name.indexOf(rights[i].right_name) > 0) {
									isHave = true;
									break;
								}
							}
							if(callback)
								callback(isHave);
							//								console.log($rootScope.wlwj_user_auth)
						});
					} else {
						for(var i = 0; i < $rootScope.wlwj_user_auth.length; i++) {
							if(name.indexOf($rootScope.wlwj_user_auth[i].right_name) > 0) {
								isHave = true;
								break;
							}
						}
						if(callback)
							callback(isHave);
					}
				}
			},
			//分类查询
			get_all_user_auth: function(callback) {
				//执行回调访问
				var that = this;
				if($rootScope.wlwj_user_auth == undefined || $rootScope.wlwj_user_auth == '') {
					//请求权限
					get_user_auth_http(function() {
						//获取权限
						var types = that.get_userauth_type();
						var items = that.get_userauth_name();
						if(callback)
							callback(types, items);
					});
				} else {
					var types = that.get_userauth_type();
					var items = that.get_userauth_name();
					if(callback)
						callback(types, items);
				}
				return items;
			},
			//大分类
			get_userauth_type: function() {
				var items = new Object();
				if($rootScope.wlwj_user_auth != undefined && $rootScope.wlwj_user_auth != '') {
					for(var i = 0; i < $rootScope.wlwj_user_auth.length; i++) {
						var item = $rootScope.wlwj_user_auth[i];
						items[item.right_type] = item.right_type;
					}
				}
				return items;
			},
			//小分类
			get_userauth_name: function() {
				var items = new Object();
				if($rootScope.wlwj_user_auth != undefined && $rootScope.wlwj_user_auth != '') {
					for(var i = 0; i < $rootScope.wlwj_user_auth.length; i++) {
						var item = $rootScope.wlwj_user_auth[i];
						var name = item.right_name;
						//权限名称对应
						//						name = (name == "企业视频" ? "明星企业" : name);
						//						name = (name == "优惠券一览" ? "优惠券" : name);
						//权限名称对应
						items[name] = name;
					}
				}
				return items;
			},
			//用户当前模式 买家/卖家
			get_issue_type_class: function() {
				get_issue_type_class_pop();
			}
		};
	})

	//聊天信息
	libs.service("ChatInfo", function() {
		function save_chat_loginItem(chat_url, login_code, soket_url) {
			localStorage.setItem("chat_url", chat_url);
			localStorage.setItem("login_code", login_code);
			localStorage.setItem("soket_url", soket_url);
		}

		function get_chatInfo() {
			var chatInfo = new Object();
			chatInfo['chat_url'] = localStorage.getItem("chat_url");
			chatInfo['login_code'] = localStorage.getItem("login_code");
			chatInfo['soket_url'] = localStorage.getItem("soket_url");
			return chatInfo;
		}
		return {
			save_chat_loginInfo: function(chat_url, login_code, soket_url) {
				//console.log(chat_url);
				return save_chat_loginItem(chat_url, login_code, soket_url);
			},
			get_isInfos: function() {
				var chatInfos = get_chatInfo();
				return chatInfos.chat_url == null ? false : true;
			},
			get_chatInfos: function() {
				var chatInfos = get_chatInfo();
				return chatInfos;
			},
			get_chatUrl: function() {
				var chatInfos = get_chatInfo();
				return chatInfos.chat_url == null ? '' : chatInfos.chat_url;

			},
			get_chatLoginCode: function() {
				var chatInfos = get_chatInfo();
				return chatInfos.login_code == null ? '' : chatInfos.login_code;
			},
			get_chatSoketUrl: function() {
				var chatInfos = get_chatInfo();
				return chatInfos.soket_url == null ? '' : chatInfos.soket_url;
			},
			clear_chatInfo: function() {
				localStorage.removeItem("chat_url");
				localStorage.removeItem("login_code");
				localStorage.removeItem("soket_url");
			}
		}
	})

	//页面跳转操作
	libs.service("GoPage", function($state, $rootScope, $ionicHistory, $ionicViewSwitcher, $window, $timeout, $interval, Auth) {

		var tabs = ['home', 'classes', 'findus', 'cart', 'center'];
		var timers = undefined;

		//跳转路由
		function go_statesPage(name, attrs, option) {

			if(name == "tab_cart") {
				$state.go('tab.cart', undefined, option);
			} else {
				//tabs的页面
				angular.forEach(tabs, function(v) {
					var isgo = $state.current.views['tab-' + v];
					if(isgo != undefined) {
						if(option && option.location === 'replace') {
							$ionicHistory.currentView($ionicHistory.backView());
						}
						if(attrs == undefined) {
							$state.go('tab.' + v + '-' + name, undefined, option);
						} else {
							$state.go('tab.' + v + '-' + name, attrs, option);
						}
						return false;
					}
				});
			}
		}

		//前一个页面对象
		function get_backViews() {
			var views = $ionicHistory.viewHistory().views;
			var items = new Array
			for(var view in views) {
				items.push(views[view]);
			}
			return items[items.length - 1];
		}

		//tab页面跳转
		function go_backtabPage(page) {
			var views = $ionicHistory.viewHistory().views;
			var count = 0;
			for(var view in views) {
				if(view != null)
					count--;
			}
			if(count < 0)
				$rootScope.$ionicGoBack(count + 1);
			$state.go("tab." + page);
		}

		//tab页面跳转
		function go_backIndex(index, name) {
			if(index == undefined || index == null) index = -1;
			if(name == undefined || name == null) name = 'back';
			$rootScope.$ionicGoBack(index);
			$ionicViewSwitcher.nextDirection(name);
		}

		//外部链接
		//_self: WebView浏览器
		//_blank: app内置浏览器
		//_system: 系统浏览器
		function go_link_http(obj) {
			if(window.cordova && window.cordova.plugins) {
				window.cordova.InAppBrowser.open(obj.link_http, '_blank', 'location=no,footer=yes,toolbar=no,toolbarposition=top,closebuttoncaption=关闭,hidenavigationbuttons=yes');
			} else {
				window.open(obj.link_http);
			}
		}

		//广告页跳转
		function go_advsPage(page) {
			if(page.indexOf("https") >= 0 || page.indexOf("http") >= 0) {
				if(window.cordova && window.cordova.plugins) {
					window.cordova.InAppBrowser.open(page, '_blank', 'location=no,toolbar=yes,toolbarposition=top,closebuttoncaption=关闭');
				} else {
					window.open(page);
				}
			} else {
				window.location.href = page;
			}
		}

		//推送跳转页面
		//1=>'spike',//秒杀  - seckilldetail
		//2=>'groupbuy',//团购
		//3=>'timebuy',//限时抢购
		//4=>'auction',//拍卖
		//5=>'newtest',//新品测试
		//6=>'newsend',//新品赠送
		//7=>'newnotice',//新品公告
		function go_pushPage(type, pushid, kind) {
			//首页
			if(type == 1) {
				go_backtabPage('home');
			}
			//活动
			if(type == 2) {
				if(kind == 1)
					go_statesPage('seckilldetail', {
						'act_id': pushid,
					});
				if(kind == 2)
					go_statesPage('groupbuydetail', {
						'act_id': pushid,
					});
				if(kind == 3)
					go_statesPage('panicbuyingdetail', {
						'act_id': pushid
					});
				if(kind == 4)
					go_statesPage('panicauctiondetail', {
						'act_id': pushid,
						'goods_id': 0
					});
				if(kind == 5)
					go_statesPage('newtest_detail', {
						'act_id': pushid
					});
				if(kind == 6)
					go_statesPage('newsend_detail', {
						'act_id': pushid
					});
				if(kind == 7)
					go_statesPage('newnotice_detail', {
						'act_id': pushid
					});
			}
			//店铺
			if(type == 3) {
				go_statesPage('first', {
					'index': 0,
					'store_id': pushid,
					'coupon_id': 0
				});
			}
			//商品
			if(type == 4) {
				go_statesPage('productdetail', {
					'goods_id': pushid,
					'type': 'goods'
				});
			}
			//商户推送
			if(type == 5) {
				//弹出页面
				$rootScope.showpushMessage(pushid);
			}
		}

		//跳转平台客服
		function gotolive800(order_id, store_id) {
			/*if(window.cordova && window.cordova.plugins) {
				//一个是内部打开
				window.cordova.InAppBrowser.open("https://v1.live800.com/live800/chatClient/chatbox.jsp?companyID=833110&configID=43818&jid=4732563954&s=1", '_blank', 'location=no,toolbar=yes,toolbarposition=top,closebuttoncaption=关闭');
			} else {
				//web端打开qq的方法再取寻找
				window.open("https://v1.live800.com/live800/chatClient/chatbox.jsp?companyID=833110&configID=43818&jid=4732563954&s=1");
			}*/
			go_statesPage('live800', {});
		}
		//跳转聊天
		function gototxcall(order_id, store_id) {
			//跳转市场
			var member_id = 0;
			var info = Auth.get_loginInfo();
			if(info != undefined && info.member_id)
				member_id = info.member_id;
			/*
			var url = HTTP_CHAT1_URL + "?order_id=" + order_id + "&store_id=" + store_id + "&member_id=" + member_id;
			if(window.cordova && window.cordova.plugins) {
				window.cordova.InAppBrowser.open(url, '_blank', 'location=no,toolbar=yes,toolbarposition=top,closebuttoncaption=关闭');
			} else {
				window.open(url);
			}*/
			go_statesPage('livechat1', {
				'order_id': order_id,
				'store_id': store_id,
				'member_id': member_id
			});
		}

		function gototxcall2(order_id, store_id, uid, code, wckey) {
			//跳转市场
			var member_id = 0;
			var info = Auth.get_loginInfo();
			if(info != undefined && info.member_id)
				member_id = info.member_id;
			/*var url = HTTP_CHAT2_URL + "?uid=" + uid + "&code=" + code + "&vvckey=" + wckey;
			if(window.cordova && window.cordova.plugins) {
				window.cordova.InAppBrowser.open(url, '_blank', 'location=no,toolbar=yes,toolbarposition=top,closebuttoncaption=关闭');
			} else {
				window.open(url);
			}*/
			go_statesPage('livechat2', {
				'order_id': order_id,
				'store_id': store_id,
				'member_id': member_id,
				'uid': uid,
				'code': code,
				'wckey': wckey
			});
		}

		function gototxcall3(uid, code, wckey) {
			/*var url = HTTP_CHAT2_URL + "?uid=" + uid + "&code=" + code + "&vvckey=" + wckey;
			if(window.cordova && window.cordova.plugins) {
				window.cordova.InAppBrowser.open(url, '_blank', 'location=no,toolbar=yes,toolbarposition=top,closebuttoncaption=关闭');
			} else {
				window.open(url);
			}*/
			go_statesPage('livechat3', {
				'uid': uid,
				'code': code,
				'wckey': wckey
			});
		}

		//定义滚动条的高度
		function listenObj($scope, topH, bottomH , tabH) {
			//定时器1秒更新一次
			if(timers != undefined)
				$interval.cancel(timers);
			//定时器
			timers = $interval(function() {
				//计算滚动
				calObj($scope, topH, bottomH , tabH);
			}, 1000);
		}

		//计算高度
		function calObj($scope, topH, bottomH,tabH) {
			/*
			//统一做法
			var lan = 0; //这是状态栏，只有ios的APP才有
			//var bars = document.getElementById("nav-bar-title");
			
			var bars = document.getElementsByClassName("header");
			
			//console.log(bars[0].offsetHeight);
			//if(window.cordova && window.cordova.plugins && ionic.Platform.isIOS()) {
			//	lan = 20;
			//}
			
			var bar = 44;
			if(bars.length>0){
				bar = bars[0].offsetHeight;
			}
			*/
			//整体高度
			var all = $window.innerHeight;
			//滚动条可视范围
			$scope.myObj = {
				"height": all - topH - bottomH - tabH + "px"
			};
			console.log(all - topH - bottomH - tabH + "px" +',all='+all+',topH='+topH +',bottomH='+bottomH +',tabH='+tabH);
		}

		function setWechatTitle(title) {
			document.title = title;
			// hack在微信等webview中无法修改document.title的情况  
			$body = $('body');
			var $iframe = $('<iframe src="/images/iframe.png"></iframe>').on('load', function() {
				setTimeout(function() {
					$iframe.off('load').remove()
				}, 0)
			}).appendTo($body)
		}

		return {
			go_toQQ: function(qq) {
				if(window.cordova && window.cordova.plugins) {
					//一个是打开QQ，一个是打开QQ群
					window.cordova.InAppBrowser.open("mqqwpa://im/chat?chat_type=wpa&uin=" + qq + "&version=1&src_type=web&web_src=oicqzone.com", '_system', 'location=no,toolbar=yes,toolbarposition=top,closebuttoncaption=关闭');
					//window.cordova.InAppBrowser.open("mqqapi://card/show_pslcard?src_type=internal&version=1&uin=" + qq + "&card_type=group&source=external", '_system');
				} else {
					//web端打开qq的方法再取寻找
					window.open("http://wpa.qq.com/msgrd?v=3&uin=" + qq + "&site=qq&menu=yes");
					//window.open("mqqapi://card/show_pslcard?src_type=internal&version=1&uin=" + qq + "&card_type=group&source=external");
				}
			},
			go_tolive800: function() {
				gotolive800();
			},
			go_txcall: function(order_id, store_id) {
				gototxcall(order_id, store_id);
			},
			go_txcall2: function(order_id, store_id, uid, code, wckey) {
				gototxcall2(order_id, store_id, uid, code, wckey);
			},
			go_txcall3: function(uid, code, wckey) {
				gototxcall3(uid, code, wckey);
			},
			go_link: function(url) {
				go_link_http({
					link_http: url
				});
			},
			//
			go_replace: function(name, attrs) {
				//tabs的页面
				go_statesPage(name, attrs, {
					location: 'replace'
				});
			},
			//跳转路由
			go_states: function(name, attrs) {
				//tabs的页面
				go_statesPage(name, attrs);
			},
			//跳转顶部
			get_backViews: function() {
				//tabs的页面
				return get_backViews();
			},
			//跳转顶部
			go_tabPage: function(page) {
				//tabs的页面
				go_backtabPage(page);
			},
			//指定回退
			go_back: function(index, name) {
				go_backIndex(index, name);
			},
			//回退并下一页
			go_states_back: function(name, attrs, index) {
				go_backIndex(index);
				$timeout(function() {
					go_statesPage(name, attrs);
					$ionicViewSwitcher.nextDirection("forward");
				}, 300);
			},
			//登录页面
			go_login: function() {
				go_statesPage('t-login');
			},
			//推送打开页面
			go_push: function(type, pushid, kind, goodsid) {
				go_pushPage(type, pushid, kind, goodsid);
			},
			go_advs: function(page) {
				go_advsPage(page);
			},
			//初始化顶部
			init_top: function($scope, topH, bottomH, tabH, topH2, topH3) {
				//统一做法
				var lan = 0; //这是状态栏，只有ios的APP才有
				
				var barheader = document.getElementsByClassName("bar-header");//头部标题栏
				if(typeof topH === "undefined"){
					topH = 44;
				}
				if(barheader.length>0){
					angular.forEach(barheader, function(obj) {
						if(obj.offsetHeight>0){
							topH = obj.offsetHeight;
						}
					});
				}
				if(typeof bottomH === "undefined"){
					bottomH = 30;
				}
				if(typeof tabH === "undefined"){
					tabH = 0;
				}
				/*
				var barheader = document.getElementsByClassName("bar-header");//头部标题栏
				var hasheader = document.getElementsByClassName("has-header");//容器栏
				
				if(window.cordova && window.cordova.plugins && ionic.Platform.isIOS() ) {
					//lan = 20;
				}
					lan = 20;//iphone时，补充20高度
					
					//iphoneX场合，因为有刘海，高度再增加20px
					if(screen.height==812 && screen.width==375)
					{
						var lan = 40;//iphoneX时，补充40高度
					}
				//标题栏高度
				angular.forEach(barheader, function(obj) {
					obj.style.height = topH +lan+'px';//头部的高度
					obj.style.paddingTop = lan+'px';//头部上余白增加40px
				});
						
				//容器栏距标题的高度
				angular.forEach(hasheader, function(obj) {
					obj.style.top = topH +lan+'px';
					if(bottomH>0){
						obj.style.bottom =bottomH+'px';
					}
				});
				*/
				//整体高度
				var all = $window.innerHeight;
				//定时侦听
				listenObj($scope, topH+lan, bottomH , tabH);
				//console.log(bars[0].parentNode);
				//console.log('all='+all+',lan='+lan+',bar='+bar+',topH='+topH +',tabH='+tabH);
				//定时侦听
				$scope.s_myObj = {
					"height": all - lan - topH - topH2 - tabH + "px"
				}
				$scope.t_myObj = {
					"height": all - lan - topH - topH3 - tabH + "px"
				}
				$scope.topObj = { //商品搜索画面用
					"top": lan + topH + "px"
				};
				//console.log('lan='+lan+',bar='+bar);
				$scope.contentObj = { //动态调整可视范围
					"padding-top": lan + topH + "px"
				};
				$scope.myObj_Search = { //搜索页面可视
					"height": all - lan - topH + "px"
				};
			},
			//首页调整顶部和底部
			init_top_home: function($scope) {
				var topH = 44;
				var bottomH = 49;

				var barheader = document.getElementsByClassName("header");//头部标题栏
				var tab_nav = document.getElementsByClassName("tab-nav");//底部导航栏
				
				if(barheader.length>0){
					angular.forEach(barheader, function(obj) {
						if(obj.offsetHeight>0){
							topH = obj.offsetHeight;
						}
					});
				}
				if(tab_nav.length>0){
					bottomH = tab_nav[0].offsetHeight;
				}
				
				//定时侦听
				listenObj($scope, topH, bottomH , 0);
				
			},
			//普通页面（调整顶部和底部）
			init_top_bottom: function($scope) {
				var topH = 44;
				var bottomH = 44;

				var barheader = document.getElementsByClassName("bar-header");//头部标题栏
				var barfooter = document.getElementsByClassName("bar-footer");//底部按钮
				
				if(barheader.length>0){
					angular.forEach(barheader, function(obj) {
						if(obj.offsetHeight>0){
							topH = obj.offsetHeight;
						}
					});
				}
				if(barfooter.length>0){
					bottomH = barfooter[barfooter.length-1].offsetHeight;
				}
				if(typeof $scope.isShowAddBtn === "undefined" || $scope.isShowAddBtn== false){
					bottomH = 0;
				}
				//整体高度
				var all = $window.innerHeight;
				//滚动条可视范围
				var myObjHeight = all - topH - bottomH;
				$scope.myObj = {
					"height": myObjHeight + "px"
				};
				console.log('init_top_bottom height='+myObjHeight + "px");
			},
			//个人中心页面（调整底部）
			init_bottom: function($scope) {
				var bottomH = 49;

				var barfooter = document.getElementsByClassName("tab-nav");//底部按钮
				
				if(barfooter.length>0){
					bottomH = barfooter[barfooter.length-1].offsetHeight;
				}
				
				//整体高度
				var all = $window.innerHeight;
				//滚动条可视范围
				$scope.myObj = {
					"height": all - bottomH + "px"
				};
				
			},
		};
	})

	//对话框相关
	libs.service("GoDialog", function($ionicPopup, $ionicActionSheet, $timeout, $ionicBackdrop, $window,$ionicModal) {

		return {
			//菊花加载
			loading: function(isShow, title) {
				//再判断是否要
				if(isShow) {
					$ionicBackdrop.retain();
					$timeout(function() {
						var items = document.getElementsByClassName("backdrop");
						items[0].innerHTML = "<div style='position: absolute;top: 45%;left:10%;width:80%;color: white;font-size: 0.65rem;'><div style='width: 50%;margin: auto;background-color: rgba(0,0,0,0.3);border-radius: 0.5rem;padding: 0.5rem;'>" + title + "</div></div>";
					});
				} else {
					$ionicBackdrop.release();
					var items = document.getElementsByClassName("backdrop");
					$timeout(function() {
						var items = document.getElementsByClassName("backdrop");
						items[0].innerHTML = "";
					});
				}
			},
			//消息提示
			toast: function(message) {
				//创建toast对象
				var toastDiv = document.createElement('div');
				toastDiv.innerHTML = message;
				toastDiv.setAttribute("class", "toast");
				document.body.appendChild(toastDiv);
				//设置消失时间
				setTimeout(function() {
					var d = 0.5;
					toastDiv.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
					toastDiv.style.opacity = '0';
					$timeout(function() {
						document.body.removeChild(toastDiv)
					}, d * 1000);
				}, 2000);
			},
			//上拉菜单 titleText标题 cancelText取消按钮 buttons其他按钮  第一个是0 最后一个是取消
			// buttons = [{text:'手机号登录',style:'<i class="icon iconfont icon-shouji"></i>'},
			//            {text:'QQ登录',style:'<i class="icon iconfont icon-shouji"></i>'}}];
			sheet: function(titleText, cancelText, buttons, callback) {
				var shows = new Array();
				if(window.cordova && window.cordova.plugins) {
					for(var i = 0; i < buttons.length; i++) {
						shows.push(buttons[i].text);
					}
				} else {
					for(var i = 0; i < buttons.length; i++) {
						shows.push({
							text: buttons[i].style + buttons[i].text
						});
					}
				}
				if(window.cordova && window.cordova.plugins) {
					var options = {
						title: titleText,
						buttonLabels: shows,
						addCancelButtonWithLabel: cancelText,
						androidEnableCancelButton: true,
						winphoneEnableCancelButton: true
					};
					window.plugins.actionsheet.show(options, function(btnIndex) {
						if(callback)
							callback(btnIndex - 1);
					});
				} else {
					var options = {
						buttons: shows,
						titleText: titleText,
						cancelText: cancelText,
						cancel: function() {
							if(callback)
								callback(buttons.length);
						},
						buttonClicked: function(index) {
							if(callback)
								callback(index);
							return true;
						}
					};
					$ionicActionSheet.show(options);
				}
			},
			//对话框
			confirm: function(title, message, callOK, callCancel) {
				//				if(window.cordova && window.cordova.plugins) {//把原生的注释
				//					navigator.notification.confirm(message, function(btnIndex) {
				//						// no button = 0, 'OK' = 1, 'Cancel' = 2
				//						if(btnIndex == 1) {
				//							if(callCancel)
				//								callCancel();
				//						} else if(btnIndex == 2) {
				//							if(callOK)
				//								callOK();
				//						}
				//					}, title, ['取消', '确定']);
				//				} else {
				$ionicPopup.confirm({
					isConfirm: true, //传isConfirm，调用自定义的popup css
					title: title,
					template: message,
					buttons: [{
						text: '取消',
						onTap: function(e) {
							if(callCancel)
								callCancel();
						}
					}, {
						text: '确定',
						type: "buttonOrange",
						onTap: function(e) {
							if(callOK)
								callOK();
						}
					}]
				});
				//				}
			},
			//提示框
			alert: function(title, message, callOK) {
				//				if(window.cordova && window.cordova.plugins) {//把原生的注释
				//					navigator.notification.alert(message, function() {
				//						if(callOK)
				//							callOK();
				//					}, title, '确定');
				//				} else {
				$ionicPopup.alert({
					isConfirm: true,
					cssClass:"",
					title: title,
					template: message,
					buttons: [{
						text: '确定',
						type: "buttonOrange"
					}]
				}).then(function(e) {
					if(callOK)
						callOK();
				});
				//				}
			},
			//查看大图，参数：图片地址
			showBigImg: function(imgUrl) {
				if(!imgUrl) {
					this.toast("对不起，找不到图片！");
					return;
				};
				$ionicBackdrop.retain();
				var items = document.getElementsByClassName("backdrop");
				var maxHeight = Math.floor($window.innerHeight * 0.7);
				items[0].innerHTML = "<div id='backdrop_img' style='height: 100%;'><div style='text-align:center; position: absolute; left: 0; right: 0; top: 50%; margin-top: -50%;'><img style='width: 90%; max-height:" + maxHeight + "px;'src='" + imgUrl + "' /></div></div>";
				var backdrop = document.getElementById("backdrop_img");
				backdrop.addEventListener("click", function(evt) {
					$ionicBackdrop.release();
					items[0].innerHTML = "";
				}, false);
			},
			//选择
			showSelect: function(title,selectItems,selectValue,callback) {
				$ionicModal.fromTemplateUrl('templates/modal/select.html', {
					animation: 'slide-in-up'
				}).then(function(modal) {
					//显示页面
					modal.show();
					modal.scope.selectObj = {"height": 250 + "px"};
					modal.scope.selectItems = selectItems;
					modal.scope.selectTitle = title;
					modal.scope.inputs = new Object();
					if(selectValue != undefined) {
					   modal.scope.inputs.selectValue = selectValue.id;
					   modal.scope.inputs.selectObject = selectValue;
				    }
					//取消选择
					modal.scope.cancelSelect = function($event) {
						modal.hide();
						document.getElementsByTagName("body")[0].classList.remove("modal-open");
					};
					//确定选择
					modal.scope.doneSelect = function($event) {
						modal.hide();
						document.getElementsByTagName("body")[0].classList.remove("modal-open");
						callback(modal.scope.inputs.selectObject);
					};
					modal.scope.serverSideChange = function(item) {
						modal.scope.inputs.selectObject = item;
					};
				});
			}
		};
	})

	//支付相关
	libs.service("GoPay", function(Http, GoWapAuth) {

		//微信内置浏览器
		function isWeiXin() {
			var ua = window.navigator.userAgent.toLowerCase();
			if(ua.match(/MicroMessenger/i) == 'micromessenger') {
				return true;
			} else {
				return false;
			}
		}

		//共通支付
		return {
			//订单支付
			do_pay: function(fields, pay_id, callOK, callFail) {
				if(window.cordova && window.cordova.plugins) {
					//如果是插件模式
					if(pay_id == 1) {
						//参数
						var params = {
							partnerid: fields.partnerid, //微信支付分配的商户号
							prepayid: fields.prepayid, //预支付交易会话ID
							noncestr: fields.noncestr, //随机字符串
							timestamp: fields.timestamp, //时间戳
							sign: fields.sign //签名
						};
						//微信支付
						Wechat.sendPaymentRequest(params, function(successResults) {
							if(callOK)
								callOK();
						}, function() {
							if(callFail)
								callFail();
						});
					} else if(pay_id == 2) {
						//因为接口返回的是字符串
						cordova.plugins.AliPay.pay(fields, function(successResults) {
							if(callOK)
								callOK();
						}, function(errorResults) {
							if(callFail)
								callFail();
						});
					} else {
						if(callFail)
							callFail();
					}
				} else {
					//微信内置
					if(isWeiXin()) {
						//参数
						GoWapAuth.execpay(fields);
					} else {
						//web模式
						if(callFail)
							callFail();
					}
				}
			}
		};
	})

	//分享相关
	libs.service("GoShare", function(Http) {

		//标题
		function getShareTitle(params) {
			if(params.title != undefined) {
				return params.title;
			} else {
				return "未来万家";
			}
		}
		//内容
		function getShareDesc(params) {
			if(params.desc != undefined) {
				return params.desc;
			} else {
				return "不断完善标准、开拓创新、勇于超越，客户的满意是未来之星人永恒的追求。";
			}
		}
		//图片
		function getShareThumb(params) {
			if(params.thumb != undefined) {
				return params.thumb;
			} else {
				return HTTP_SHARE_URL + "logo.png";
			}
		}
		//链接内容
		function getShareLink(params) {
			if(params.link != undefined) {
				return HTTP_SHARE_URL + "index.html#/tab/" + params.link;
			} else {
				return HTTP_SHARE_URL + "index.html#/tab/home";
			}
		}
		//共通
		return {
			//分享
			do_share: function(params, index) {
				var title = getShareTitle(params);
				var desc = getShareDesc(params);
				var thumb = getShareThumb(params);
				var links = getShareLink(params);

				if(window.cordova && window.cordova.plugins) {
					if(index == 1) {
						Wechat.share({
							message: {
								title: title,
								description: desc,
								thumb: thumb,
								media: {
									type: Wechat.Type.WEBPAGE,
									webpageUrl: links
								}
							},
							scene: Wechat.Scene.SESSION // 分享好友
						}, function() {
							GoDialog.alert('提示', '分享成功');
						}, function(reason) {
							GoDialog.alert('提示', "分享失败: " + reason);
						});
					}
					if(index == 2) {
						Wechat.share({
							message: {
								title: title,
								description: desc,
								thumb: thumb,
								media: {
									type: Wechat.Type.WEBPAGE,
									webpageUrl: links
								}
							},
							scene: Wechat.Scene.TIMELINE // 分享朋友圈
						}, function() {
							GoDialog.alert('提示', '分享成功');
						}, function(reason) {
							GoDialog.alert('提示', "分享失败: " + reason);
						});
					}
					if(index == 3) {
						var args = {};
						args.scene = QQSDK.Scene.QQ; //QQSDK.Scene.QQZone,QQSDK.Scene.Favorite
						args.title = title;
						args.description = desc;
						args.image = thumb;
						args.url = links;
						QQSDK.shareNews(function() {
							GoDialog.alert('提示', '分享成功');
						}, function(failReason) {
							GoDialog.alert('提示', "分享失败: " + failReason);
						}, args);
					}
					if(index == 4) {
						var args = {};
						args.scene = QQSDK.Scene.QQZone; //QQSDK.Scene.QQZone,QQSDK.Scene.Favorite
						args.title = title;
						args.description = desc;
						args.image = thumb;
						args.url = links;
						QQSDK.shareNews(function() {
							GoDialog.alert('提示', '分享成功');
						}, function(failReason) {
							GoDialog.alert('提示', "分享失败: " + failReason);
						}, args);
					}
				}
			}

		};
	})

	//品牌地址
	libs.service("GoBrandAddress", function(Http) {
		//内存数据
		var province_list = new Array();
		var city_list = new Object();
		var district_list = new Object();

		function init_http_brand($scope, type, brand_id, store_id, region_id, callback) {
			if(type == 0) {
				//取下一级
				load_http_brand($scope, type, brand_id, store_id, region_id, callback);
			} else if(type == 1) {
				//取下一级
				if(city_list[store_id + "_" + brand_id + "_" + region_id] == undefined) {
					load_http_brand($scope, type, brand_id, store_id, region_id, callback);
				} else {
					if(callback)
						callback(city_list[store_id + "_" + brand_id + "_" + region_id]);
				}
			} else if(type == 2) {
				if(district_list[store_id + "_" + brand_id + "_" + region_id] == undefined) {
					load_http_brand($scope, type, brand_id, store_id, region_id, callback);
				} else {
					if(callback)
						callback(district_list[store_id + "_" + brand_id + "_" + region_id]);
				}
			}
		}
		//网上获取数据
		function load_http_brand($scope, type, store_id, brand_id, region_id, callback) {
			var param = new Object();
			param.method = 'brand.info.getNextRegionLvl';
			param.brand_id = brand_id;
			param.store_id = store_id;
			param.region_id = region_id;
			//console.log(param);
			//post请求
			Http.post(param, function(result) {
				//绑定初始化
				if(type == 0) {
					if(result.result != null) {
						province_list = data_bind(result.result.list);
						if(callback)
							callback(province_list);
					}
				} else if(type == 1) {
					if(result.result != null) {
						city_list[store_id + "_" + brand_id + "_" + region_id] = data_bind(result.result.list);
						if(callback)
							callback(city_list[store_id + "_" + brand_id + "_" + region_id]);
					}
				} else if(type == 2) {
					if(result.result != null) {
						district_list[store_id + "_" + brand_id + "_" + region_id] = data_bind(result.result.list);
						if(callback)
							callback(district_list[store_id + "_" + brand_id + "_" + region_id]);
					}
				}
			});
		}
		//初始化绑定
		function init_bind($scope, items) {
			items.forEach(function(obj) {
				//侦听输入变化 省份选择会覆盖其他
				$scope.$watch(obj.name, function(newValue, oldValue) {
					//console.log(obj);
					//console.log(newValue);
					var i = obj.name.length;
					$scope.obj = obj.name.substring(i - 8, i);
					//判断当前输入的模型是省、市、区
					if($scope.obj != "province") {
						$scope.obj = obj.name.substring(i - 4, i);
						if($scope.obj != "city")
							$scope.obj = obj.name.substring(i - 8, i);
					}
					if($scope.obj == "province") {
						if(obj.id != undefined) {
							//动态地域第一级未选中的时候当前item置null
							if(newValue == null) {
								if($scope.listen_province)
									$scope.listen_province(null, obj.id);
							}
						} else {
							//非动态地域第一级未选中的时候当前item置null
							if(newValue == null) {
								$scope.city_items = null;
								$scope.district_items = null;
								return;
							}
						}

					} else if($scope.obj == "city") {
						if(obj.id != undefined) {
							if(newValue == null) {
								if($scope.listen_city)
									$scope.listen_city(null, obj.id);
							}
						} else
						if(newValue == null) {
							$scope.district_items = null;
							return;
						}
					}
					if(newValue == null) return;

					//省级下拉触发
					if($scope.obj == "province") {
						//数据绑定
						init_http_brand($scope, 1, $scope.input.store_id, $scope.detail.brand[obj.id].brand.id, newValue.id, function(data) {
							if($scope.listen_province)
								$scope.listen_province(data, obj.id);
						});
					}
					//市级下拉触发
					if($scope.obj == "city") {
						//数据绑定
						init_http_brand($scope, 2, $scope.input.store_id, $scope.detail.brand[obj.id].brand.id, newValue.id, function(data) {
							if($scope.listen_city)
								$scope.listen_city(data, obj.id);
						});
					}
					//区级下拉
					if($scope.obj == "district") {
						if($scope.listen_district)
							$scope.listen_district(data, obj.id);
					}
				});
			});
		}
		//数据组装
		function data_bind(data) {
			var items = new Array();
			for(var i = 0; i < data.length; i++) {
				//				if(data[i].id == undefined)
				items.push({
					id: data[i][0],
					name: data[i][1]
				});
				//				else
				//					items.push({ id: data[i].id, name: data[i].name });
			}
			return items;
		}
		return {
			/**画面单个三级联动
			 * items = name,callback
			 * @param {Object} items
			 */
			init_load_brand: function($scope, items) {
				//初始化数组
				$scope.province_items = new Array();
				//先初始化第一个数据
				init_bind($scope, items);
				//初始化数据绑定

			},
			init_province: function($scope, i, brand_id) {
				//console.log(i);
				//console.log(brand_id);
				init_http_brand($scope, 0, $scope.input.store_id, brand_id, 0, function(data) {
					$scope.detail.brand[i].province_items = data;

				});
			}
		}
	})

	//地址管理
	libs.service("GoAddress", function(Http) {
		//内存数据
		var province_list = new Array();
		var city_list = new Object();
		var district_list = new Object();

		//省市区联动通用组件
		function init_http($scope, type, parent_id, callback) {
			if(type == 0) {
				if(province_list.length == 0) {
					//取下一级
					load_http($scope, type, parent_id, callback);
				} else {
					if(callback)
						callback(province_list);
				}
			} else if(type == 1) {
				//取下一级
				if(city_list[parent_id] == undefined) {
					load_http($scope, type, parent_id, callback);
				} else {
					if(callback)
						callback(city_list[parent_id]);
				}
			} else if(type == 2) {
				if(district_list[parent_id] == undefined) {
					load_http($scope, type, parent_id, callback);
				} else {
					if(callback)
						callback(district_list[parent_id]);
				}
			}
		}

		//网上获取数据
		function load_http($scope, type, parent_id, callback) {
			var param = new Object();
			if(parent_id != "") {
				param.method = 'region.info.getNextLvl';
				param.region_id = parent_id;
			} else {
				param.method = 'region.info.init';
				param.region_id = "";
			}
			//post请求
			Http.post(param, function(result) {
				//绑定初始化
				if(type == 0) {
					if(result.result != null) {
						province_list = data_bind(result.result.data[0].list);
						if(callback)
							callback(province_list);
					}
				} else if(type == 1) {
					if(result.result != null) {
						city_list[parent_id] = data_bind(result.result.list);
						if(callback)
							callback(city_list[parent_id]);
					}
				} else if(type == 2) {
					if(result.result != null) {
						district_list[parent_id] = data_bind(result.result.list);
						if(callback)
							callback(district_list[parent_id]);
					}
				}
			});
		}
		//初始化绑定
		function init_bind($scope, items) {
			items.forEach(function(obj) {
				//侦听输入变化 省份选择会覆盖其他
				$scope.$watch(obj.name, function(newValue, oldValue) {
					if($scope.isUnwatch) return; //不进行侦听
					//					$scope.agenter_list = new Object();
					var i = obj.name.length;
					$scope.obj = obj.name.substring(i - 8, i);
					//判断当前输入的模型是省、市、区
					if($scope.obj != "province") {
						$scope.obj = obj.name.substring(i - 4, i);
						if($scope.obj != "city")
							$scope.obj = obj.name.substring(i - 8, i);
					}
					if($scope.obj == "province") {
						if(obj.id != undefined) {
							//动态地域第一级未选中的时候当前item置null
							if(newValue == null) {
								if($scope.listen_province)
									$scope.listen_province(null, obj.id);
							}
						} else {
							//非动态地域第一级未选中的时候当前item置null
							if(newValue == null) {
								$scope.city_items = null;
								$scope.district_items = null;
								return;
							}
						}

					} else if($scope.obj == "city") {
						if(obj.id != undefined) {
							if(newValue == null) {
								if($scope.listen_city)
									$scope.listen_city(null, obj.id);
							}
						} else
						if(newValue == null) {
							$scope.district_items = null;
							return;
						}
					}
					if(newValue == null) return;

					//省级下拉触发
					if($scope.obj == "province") {
						//数据绑定
						init_http($scope, 1, newValue.id, function(data) {
							$scope.city_items = data;
							if($scope.listen_province)
								$scope.listen_province(data, obj.id);
						});
					}
					//市级下拉触发
					if($scope.obj == "city") {
						//数据绑定
						init_http($scope, 2, newValue.id, function(data) {
							$scope.district_items = data;

							if($scope.listen_city)
								$scope.listen_city(data, obj.id);
						});
					}
					//区级下拉
					if($scope.obj == "district") {
						if($scope.listen_district)
							$scope.listen_district(data, obj.id);
					}
				});
			});
		}
		//初始化绑定
		function init_bind_more($scope, items) {
			//分组
			items.forEach(function(array) {
				//组内控件
				array.forEach(function(obj) {
					//侦听输入变化 省份选择会覆盖其他
					$scope.$watch(obj.name, function(newValue, oldValue) {
						if($scope.isUnwatch) return; //不进行侦听
						if(newValue == null) return;
						//省级下拉触发
						if(obj.level == 1) {
							//数据绑定
							init_http($scope, 1, newValue.id, function(data) {
								//设置值
								if(obj.callback)
									obj.callback(newValue);
							});
						}
						//市级下拉触发
						if(obj.level == 2) {
							//数据绑定
							init_http($scope, 2, newValue.id, function(data) {
								//设置值
								if(obj.callback)
									obj.callback(newValue);
							});
						}
						//区级下拉
						if(obj.level == 3) {
							if(obj.callback)
								obj.callback(newValue);
						}
					});
				});
			});
		}
		//数据组装
		function data_bind(data) {
			var items = new Array();
			if(data != undefined){
				for(var i = 0; i < data.length; i++) {
					items.push({
						id: data[i][0],
						name: data[i][1]
					});
				}
			}
			return items;
		}
		//数据初始化
		function datarelative(initdata) {
			var data = {
				list1: [],
				value1: '',
				list2: [],
				value2: '',
				list3: [],
				value3: ''
			}

			var initData = initdata || [];
			for(var i = 0; i < 3 && i < initData.length; i++) {
				var l = initData[i].list || [];
				var v = initData[i].value || '';
				for(var j = 0; j < l.length; j++) {
					data['list' + (i + 1)].push({
						id: l[j][0],
						name: l[j][1]
					});
					//选中obj
					if(v == l[j][0])
						data['value' + (i + 1)] = {
							id: l[j][0],
							name: l[j][1]
						};
				}
			}

			return data;
		}
		
		return {
			/**画面单个三级联动
			 * items = name,callback
			 * @param {Object} items
			 */
			init_load: function($scope, items) {
				//初始化数组
				$scope.province_items = new Array();
				$scope.city_items = new Array();
				$scope.district_items = new Array();
				//先初始化第一个数据
				init_bind($scope, items);
				//初始化数据绑定
				init_http($scope, 0, "", function(data) {
					$scope.province_items = data;
				});
			},

			/**画面多个三级联动
			 * items = name,callback
			 * @param {Object} items
			 */
			init_load_more: function($scope, items, callback) {
				//先初始化第一个数据
				init_bind_more($scope, items);
				//初始化数据绑定
				init_http($scope, 0, "", function(data) {
					if(callback)
						callback(data);
				});
			},
			init_htp: function($scope, type, parent_id, callback) {
				init_http($scope, type, parent_id, function(data) {
					if(type == 0)
						$scope.province_items = data;
					if(type == 1)
						$scope.city_items = data;
					if(type == 2)
						$scope.district_items = data;
					if(callback)
						callback(true);
				});
			},
			//根据id查找当前选择
			init_region: function($scope, region_id, callback) {
				//初始化地区
				var param = {
					method: 'region.info.init',
					region_value: region_id
				}
				//post请求
				Http.post(param, function(res) {
					var result = datarelative(res.result.data);
					$scope.province_items = result.list1;
					$scope.city_items = result.list2;
					$scope.district_items = result.list3;
					if(callback)
						callback(result.value1, result.value2, result.value3);
				});
			},
		}
	})

	//品牌与分类的关系（必须用户登录）
	libs.service("GoCatTypeAuth", function(Http) {
		//内存数据 记录品牌
		var brand_list = new Array();
		var cat1_list = new Object(); //品牌关联
		var cat2_list = new Object(); //品牌关联_pid
		var cat3_list = new Object(); //品牌关联_pid
		//内存数据 记录非品牌
		var cat11_list = new Array(); //品牌关联
		var cat22_list = new Object(); //品牌关联_pid
		var cat33_list = new Object(); //品牌关联_pid

		//所有品牌初始化
		function init_brand_all($scope, callback) {
			var param = new Object();
			param.method = 'member.brand.getall';

			//获取全部信息
			Http.post(param, function(result) {
				if(result.result != null) {
					brand_list = data_bind(result.result.brand);
					if(callback)
						callback(brand_list);
				}
			});
		}

		//品牌初始化
		function init_brand($scope, callback) {
			var param = new Object();
			param.method = 'goods.brand.getlist';

			//获取全部信息
			Http.post(param, function(result) {
				if(result.result != null) {
					brand_list = data_bind(result.result.brand);
					if(callback)
						callback(brand_list);
				}
			});
		}
		//联动通用组件  记录品牌
		function init_http($scope, type, store_id, brand_id, cat_id, callback) {
			if(type == 0) {
				//取下一级
				if(cat1_list[store_id + "_" + brand_id] == undefined) {
					load_http($scope, type, store_id, brand_id, cat_id, callback);
				} else {
					if(callback)
						callback(cat1_list[store_id + "_" + brand_id]);
				}
			} else if(type == 1) {
				//取下一级
				if(cat2_list[store_id + "_" + brand_id + "_" + cat_id] == undefined) {
					load_http($scope, type, store_id, brand_id, cat_id, callback);
				} else {
					if(callback)
						callback(cat2_list[store_id + "_" + brand_id + "_" + cat_id]);
				}
			} else if(type == 2) {
				if(cat3_list[store_id + "_" + brand_id + "_" + cat_id] == undefined) {
					load_http($scope, type, store_id, brand_id, cat_id, callback);
				} else {
					if(callback)
						callback(cat3_list[store_id + "_" + brand_id + "_" + cat_id]);
				}
			}
		}
		//联动通用组件  记录非品牌
		function init_http_only($scope, type, cat_id, callback) {
			if(type == 0) {
				//取下一级
				if(cat11_list.length == 0) {
					load_http_only($scope, type, cat_id, callback);
				} else {
					if(callback)
						callback(cat11_list);
				}
			} else if(type == 1) {
				//取下一级
				if(cat22_list[cat_id] == undefined) {
					load_http_only($scope, type, cat_id, callback);
				} else {
					if(callback)
						callback(cat22_list[cat_id]);
				}
			} else if(type == 2) {
				if(cat33_list[cat_id] == undefined) {
					load_http_only($scope, type, cat_id, callback);
				} else {
					if(callback)
						callback(cat33_list[cat_id]);
				}
			}
		}

		//分类初始化
		function load_http($scope, type, store_id, brand_id, cat_id, callback) {
			var param = new Object();
			param.method = 'brand.info.getNextCatLvl';
			param.cat_id = cat_id;
			param.brand_id = brand_id;
			param.store_id = store_id;

			//获取全部信息
			Http.post(param, function(result) {
				//绑定初始化
				if(type == 0) {
					if(result.result != null) {
						cat1_list[store_id + "_" + brand_id] = data_bind(result.result.list);
						if(callback)
							callback(cat1_list[store_id + "_" + brand_id]);
					}
				} else if(type == 1) {
					if(result.result != null) {
						cat2_list[store_id + "_" + brand_id + "_" + cat_id] = data_bind(result.result.list);
						if(callback)
							callback(cat2_list[store_id + "_" + brand_id + "_" + cat_id]);
					}
				} else if(type == 2) {
					if(result.result != null) {
						cat3_list[store_id + "_" + brand_id + "_" + cat_id] = data_bind(result.result.list);
						if(callback)
							callback(cat3_list[store_id + "_" + brand_id + "_" + cat_id]);
					}
				}
			});
		}
		//分类初始化
		function load_http_only($scope, type, cat_id, callback) {
			var param = new Object();
			param.method = 'brand.info.getNextCatLvl';
			param.cat_id = cat_id;
			//获取全部信息
			Http.post(param, function(result) {
				//绑定初始化
				if(type == 0) {
					if(result.result != null) {
						cat11_list = data_bind(result.result.list);
						if(callback)
							callback(cat11_list);
					}
				} else if(type == 1) {
					if(result.result != null) {
						cat22_list[cat_id] = data_bind(result.result.list);
						if(callback)
							callback(cat22_list[cat_id]);
					}
				} else if(type == 2) {
					if(result.result != null) {
						cat33_list[cat_id] = data_bind(result.result.list);
						if(callback)
							callback(cat33_list[cat_id]);
					}
				}
			});
		}

		//初始化绑定
		function init_bind($scope, items) {
			items.forEach(function(obj) {
				//侦听输入变化 省份选择会覆盖其他
				$scope.$watch(obj.name, function(newValue, oldValue) {
					if($scope.isUnwatch) return; //不进行侦听
					var i = obj.name.length;
					var id = obj.id;
					var obj_cat = obj.name.substring(i - 5, i);
					if(oldValue == null)
						$scope.is_init = true;
					else
						$scope.is_init = false;
					//判断当前输入的模型是省、市、区
					if(obj_cat != "brand") {
						obj_cat = obj.name.substring(i - 4, i);
						//						if($scope.obj != "cat1")
						//							$scope.obj = obj.name.substring(i - 8, i);
					}

					if(obj_cat == "brand") {
						if(id != undefined) {
							if(newValue == null) {
								if($scope.listen_brand)
									$scope.listen_brand(null, obj.id, $scope.is_init);
							}
						} else {
							if(newValue == null) {
								$scope.cat1_items = null;
								$scope.cat2_items = null;
								$scope.cat3_items = null;
								return;
							}
						}

					} else if(obj_cat == "cat1") {
						if(id != undefined) {
							if(newValue == null) {
								if($scope.listen_cat1)
									$scope.listen_cat1(null, obj.id);
							}
						} else {
							if(newValue == null) {
								$scope.cat2_items = null;
								$scope.cat3_items = null;
								return;
							}
						}

					} else if(obj_cat == "cat2") {
						if(id != undefined) {
							if(newValue == null) {
								if($scope.listen_cat2)
									$scope.listen_cat2(null, obj.id);
							}
						} else {
							if(newValue == null) {
								$scope.cat3_items = null;
								return;
							}
						}

					}
					if(newValue == null || newValue == oldValue) return;

					//品牌关联
					if(obj_cat == "brand") {
						//数据绑定
						init_http($scope, 0, $scope.input.store_id, newValue.id, 0, function(data) {
							$scope.cat1_items = data;
							//							console.log(data);
							//设置值
							if($scope.listen_brand)
								$scope.listen_brand(data, obj.id, $scope.is_init);
						});
					}
					//一级分类
					if(obj_cat == "cat1") {
						//数据绑定
						init_http($scope, 1, $scope.input.store_id, $scope.input.brand.id, newValue.id, function(data) {
							$scope.cat2_items = data;
							$scope.cat3_items = null;
							//设置值
							if($scope.listen_cat1)
								$scope.listen_cat1(data, obj.id);
						});
					}
					//二级分类
					if(obj_cat == "cat2") {
						//数据绑定
						init_http($scope, 2, $scope.input.store_id, $scope.input.brand.id, newValue.id, function(data) {
							$scope.cat3_items = data;
							//设置值
							if($scope.listen_cat2)
								$scope.listen_cat2(data, obj.id);
						});
					}
					//三级分类
					if(obj_cat == "cat3") {
						//设置值
						if($scope.listen_cat3)
							$scope.listen_cat3(data, obj.id);
					}
				});
			});
		}
		//初始化绑定
		function init_bind_only($scope, items) {
			items.forEach(function(obj) {
				//侦听输入变化 省份选择会覆盖其他
				$scope.$watch(obj.name, function(newValue, oldValue) {
					if($scope.isUnwatch) return; //不进行侦听
					if(obj.name == "input.cat1") {
						if(newValue == null) {
							$scope.cat2_items = null;
							$scope.cat3_items = null;
						}
					}
					if(obj.name == "input.cat2") {
						if(newValue == null) {
							$scope.cat3_items = null;
						}
					}
					if(newValue == null || newValue == oldValue) return;

					//一级分类
					if(obj.name == "input.cat1") {
						//数据绑定
						init_http_only($scope, 1, newValue.id, function(data) {
							$scope.cat2_items = data;
							//设置值
							if($scope.listen_cat1)
								$scope.listen_cat1(newValue);
						});
					}
					//二级分类
					if(obj.name == "input.cat2") {
						//数据绑定
						init_http_only($scope, 2, newValue.id, function(data) {
							$scope.cat3_items = data;
							//设置值
							if($scope.listen_cat2)
								$scope.listen_cat2(newValue);
						});
					}
					//三级分类
					if(obj.name == "input.cat3") {
						//设置值
						if($scope.listen_cat3)
							$scope.listen_cat3(newValue);
					}
				});
			});
		}

		//数据组装
		function data_bind(data) {
			var items = new Array();
			for(var i = 0; i < data.length; i++) {
				if(data[i].id == undefined)
					items.push({
						id: data[i][0],
						name: data[i][1]
					});
				else
					items.push({
						id: data[i].id,
						name: data[i].name
					});
			}
			return items;
		}

		//倒回组装
		function datarelative(initdata) {
			var data = {
				list1: [],
				value1: '',
				list2: [],
				value2: '',
				list3: [],
				value3: '',
				list4: [],
				value4: '',
				list5: [],
				value5: ''
			}

			var initData = initdata || [];
			for(var i = 0; i < 5 && i < initData.length; i++) {
				var l = initData[i].list || [];
				var v = initData[i].value || '';
				for(var j = 0; j < l.length; j++) {
					data['list' + (i + 1)].push({
						id: l[j][0],
						name: l[j][1]
					})
					//选中obj
					if(v == l[j][0])
						data['value' + (i + 1)] = {
							id: l[j][0],
							name: l[j][1]
						};
				}
			}

			return data;
		}

		return {
			//所有品牌分类三级联动（品牌关联）
			init_load_all: function($scope, items) {
				//初始化数组
				if($scope.brand_items != undefined) {
					if($scope.brand_items.length == 0)
						$scope.brand_items = new Array();
				} else
					$scope.brand_items = new Array();
				$scope.cat1_items = new Array();
				$scope.cat2_items = new Array();
				$scope.cat3_items = new Array();
				//初始化品牌
				init_brand_all($scope, function(data) {
					if($scope.brand_items.length == 0)
						$scope.brand_items = data;
				});
				//先初始化第一个数据
				init_bind($scope, items);
			},
			//分类三级联动（品牌关联）
			init_load: function($scope, items) {
				//初始化数组
				if($scope.brand_items != undefined) {
					if($scope.brand_items.length == 0)
						$scope.brand_items = new Array();
				} else
					$scope.brand_items = new Array();
				$scope.cat1_items = new Array();
				$scope.cat2_items = new Array();
				$scope.cat3_items = new Array();
				//先初始化第一个数据
				init_bind($scope, items);
				//初始化品牌
				init_brand($scope, function(data) {
					if($scope.brand_items.length == 0)
						$scope.brand_items = data;
				});
			},
			//分类三级联动（非品牌关联）
			init_load_only: function($scope, items) {
				//初始化数组
				$scope.cat1_items = new Array();
				$scope.cat2_items = new Array();
				$scope.cat3_items = new Array();
				//先初始化第一个数据
				init_bind_only($scope, items);
				//初始化数据绑定
				init_http_only($scope, 0, 0, function(data) {
					$scope.cat1_items = data;
				});
			},
			init_brand: function($scope, callback) {
				init_brand($scope, function(data) {
					$scope.brand_items = data;
					if(callback)
						callback();
				});
			},
			//平台上的所有品牌，按首字母排序
			init_brandsOrderBy: function($scope, search_words, search_store_id) {
				var param = {
					method: 'member.brand.getall',
					group: true,
					search_words: search_words,
					search_store_id: search_store_id
				}
				Http.post(param, function(data) {
					$scope.brandsOrderBy = data.result.brand;
					var everyHeight = (window.innerHeight - 100) / $scope.brandsOrderBy.length;
					if(everyHeight>30){
						everyHeight = 30;
					}
					$scope.everyHeight = { //右边首字母的高度
						"height": everyHeight + "px"
					};
				});
			},
			//根据id查找当前选择
			inti_cat: function($scope, cat_id, callback) {
				var param = {
					method: 'brand.info.initcat',
					inputdata: cat_id
				}
				//post请求(默认三个下拉)
				Http.post(param, function(res) {
					if(res.result.data.length > 0) {
						var result = datarelative(res.result.data[0].cats[0]);
						$scope.cat1_items = result.list1;
						$scope.cat2_items = result.list2;
						$scope.cat3_items = result.list3;
						if(callback)
							callback(result.value1, result.value2, result.value3);
					}
				});
			}
		};
	})

	//图片上传
	libs.service("GoPicture", function($http, $timeout, $ionicLoading, Auth, GoDialog) {

		var ONCE_UPLOAD_IMG_MAX = 9 //上传质量
		var UPLOAD_IMG_MAX_WIDTH = 600; //宽度
		var UPLOAD_IMG_MAX_SIZE = 5 * 1024 * 1024; //压缩图片大小

		//签名处理
		function sign(args) {
			//1.根据参数名称（系统参数和应用参数）将所要传递的参数（签名除外）按照参数名做升序排序，然后对参数名和参数值（使用UTF-8编码）链接成字符串。
			delete args.sign; //签名除外

			var keys = Object.keys(args);
			keys = keys.sort();
			var result = '';
			for(var k in args) {
				result = result + k + '=' + args[k] + '&';
			}
			//2.将此字符串加上中心会话密钥token进行一次MD5，获得十六进制字符串，转成大写格式。
			result = result + HTTP_TOKEN;
			result = hex_md5(result).toUpperCase();
			//3.将一次MD5后的字符串再次MD5，获得十六进制字符串，转成大写格式。
			result = hex_md5(result).toUpperCase();
			//4.最后把结果当做一个请求参数，名称为sign。
			return result;
		};

		function removeInputFile(id) {
			var inputFileId = id;
			var inputFile = document.getElementById(inputFileId);
			if(inputFile) {
				document.body.removeChild(inputFile);
			}
		}

		function start_upload(e) {
			console.log(e)
			var input = e.target
			var callback = this.callback || function() {};
			var inputFileId = this.fileElementId;

			if(!(input.files && input.files[0])) {
				return
			}
			if(input.files.length < 1) {
				GoDialog.toast("只能上传一个文件");
				return
			}
			var file = input.files[0];

			var Infos = Auth.get_loginInfo();

			try {

				var reader = new FileReader()
				var setObj = new Object(); //压缩参数
				setObj.width = 600; //宽度默认600
				setObj.quality = 0.7; //质量0.7
				reader.onload = function(e) {
					//获取照片方向角属性，用户旋转控制 
					EXIF.getData(file, function() {
						EXIF.getAllTags(this);
						var Orientation = EXIF.getTag(this, 'Orientation');
						//压缩
						file_compress2(e.target.result, setObj, Orientation, function(base64, blobUrl, blob) {
							$ionicLoading.hide();
							if(blobUrl) {
								if(blob.size > file.size) {
									blob = file
								}

								if(blob.size > UPLOAD_IMG_MAX_SIZE) {
									GoDialog.toast("图片压缩后不得大于2M");
									return;
								}

								var args = {
									'method': 'file.photo.upload',
									'session': Infos.user_id
								}
								var param = {
									'sign': sign(args),
									'method': args.method,
									'api_version': '1.0',
									'cellpic': blob
								};

								$http({
									url: HTTP_URL,
									method: 'POST',
									data: param,
									headers: {
										'Content-Type': undefined
									},
									transformRequest: function(data, headersGetter) {
										var formData = new FormData();
										for(var key in data) {
											formData.append(key, data[key]);
										}

										return formData;

									}
								}).success(function(data) {
									if(data == undefined) {
										//GoDialog.toast('网络异常！');
									} else if(data.error != undefined) {
										GoDialog.toast(data.msg);
									} else if(data.success === -1) {
										GoDialog.toast("session超时，重新登录");
									} else {
										callback(data);
									}
								}).error(function(e) {}).finally(function() {
									removeInputFile(inputFileId);
								});
							} else {
								// 压缩失败
								GoDialog.toast("图片压缩失败");
								removeInputFile(inputFileId);
							}
						});
					});
				}

				$ionicLoading.show({
					template: '图片处理中...'
				});
				reader.readAsDataURL(file)
			} catch(ex) {
				GoDialog.toast("图片上传失败");
				removeInputFile(inputFileId);
			}
		}

		function file_upload(cb) {

			// <input id="inputFile" type="file" name="file" class="weui_uploader_input" accept="image/*" multiple="multiple" />
			//   file.change(this.fileChange.bind(this))
			//   file.trigger('click')
			var file = document.createElement('input');
			file.setAttribute("type", "file");
			file.setAttribute("accept", "image/*");
			// file.setAttribute("multiple", "multiple");
			file.id = 'GoPicture_' + new Date().getTime();
			file.onchange = start_upload.bind({
				callback: cb,
				fileElementId: file.id
			});

			document.body.appendChild(file);

			file.click();
		}

		function dataURItoBlob(dataURI) {
			var byteString = atob(dataURI.split(',')[1]);
			var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
			var ab = new ArrayBuffer(byteString.length);
			var ia = new Uint8Array(ab);
			for(var i = 0; i < byteString.length; i++) {
				ia[i] = byteString.charCodeAt(i);
			}
			return new Blob([ab], {
				type: mimeString
			});
		}

		function dataURItoBase64(dataURI, callback) {
			var canvas = document.createElement('canvas');
			var ctx = canvas.getContext('2d');
			var img = new Image;
			img.src = dataURI;
			img.onload = function() {
				canvas.height = img.height;
				canvas.width = img.width;
				ctx.drawImage(img, 0, 0);
				var dataURL = canvas.toDataURL('image/png');
				if(callback)
					callback(dataURL);
			};
		};

		//对图片旋转处理
		function rotateImg(img, direction, canvas) {
			//最小与最大旋转方向，图片旋转4次后回到原方向   
			var min_step = 0;
			var max_step = 3;
			//var img = document.getElementById(pid);   
			if(img == null) return;
			//img的高度和宽度不能在img元素隐藏后获取，否则会出错   
			var height = img.height;
			var width = img.width;
			//var step = img.getAttribute('step');   
			var step = 2;
			if(step == null) {
				step = min_step;
			}
			if(direction == 'right') {
				step++;
				//旋转到原位置，即超过最大值   
				step > max_step && (step = min_step);
			} else {
				step--;
				step < min_step && (step = max_step);
			}
			//旋转角度以弧度值为参数   
			var degree = step * 90 * Math.PI / 180;
			var ctx = canvas.getContext('2d');
			switch(step) {
				case 0:
					canvas.width = width;
					canvas.height = height;
					ctx.drawImage(img, 0, 0);
					break;
				case 1:
					canvas.width = height;
					canvas.height = width;
					ctx.rotate(degree);
					ctx.drawImage(img, 0, -height);
					break;
				case 2:
					canvas.width = width;
					canvas.height = height;
					ctx.rotate(degree);
					ctx.drawImage(img, -width, -height);
					break;
				case 3:
					canvas.width = height;
					canvas.height = width;
					ctx.rotate(degree);
					ctx.drawImage(img, -width, 0);
					break;
			}
		}

		function file_compress2(src, obj, Orientation, cb) {
			var img = new Image();
			img.src = src;
			img.onload = function() {
				var that = this;
				try {
					// 默认按比例压缩
					var w = that.width;
					var h = that.height;
					var scale = w / h;
					var quality = 0.7; // 默认图片质量为0.7
					w = obj.width || w;
					h = obj.height || (w / scale);
					//生成canvas
					var canvas = document.createElement('canvas');
					var ctx = canvas.getContext('2d');
					// 创建属性节点
					var anw = document.createAttribute("width");
					anw.nodeValue = w;
					var anh = document.createAttribute("height");
					anh.nodeValue = h;
					canvas.setAttributeNode(anw);
					canvas.setAttributeNode(anh);
					ctx.drawImage(that, 0, 0, w, h);
					// 图像质量
					if(obj.quality && obj.quality <= 1 && obj.quality > 0) {
						quality = obj.quality;
					}
					//图片旋转
					if(Orientation != "" && Orientation != 1) {
						switch(Orientation) {
							case 6: //需要顺时针（向左）90度旋转 
								rotateImg(this, 'left', canvas);
								break;
							case 8: //需要逆时针（向右）90度旋转 
								rotateImg(this, 'right', canvas);
								break;
							case 3: //需要180度旋转 
								rotateImg(this, 'right', canvas); //转两次 
								rotateImg(this, 'right', canvas);
								break;
						}
					}
					// quality值越小，所绘制出的图像越模糊
					var base64 = canvas.toDataURL('image/jpeg', quality);
					var blob = dataURItoBlob(base64);
					var blobUrl = URL.createObjectURL(blob);

					try {
						cb && cb(base64, blobUrl, blob)
					} catch(e) {
						console.info(e);
					}

				} catch(ex) {
					cb && cb(null)
				}
			};
		}

		//拍照
		function takePhone(callback, error) {
			//quality 保存图像的质量，范围0-100
			//destinationType 返回值格式:DATA_URL=0,返回作为base64编码字符串；FILE_URL=1，返回图像的URL；NATIVE_RUL=2，返回图像本机URL
			//sourceType 设置图片来源：PHOTOLIBRARY=0，相机拍照=1
			//allowEdit 选择图片前是否允许编辑
			//encodingType JPEN = 0，PNG = 1
			//targetWidth //缩放图像的宽度（像素）
			//targetHeight //缩放图像的高度（像素）
			//popoverOptions //ios,iPad弹出位置
			//saveToPhotoAlbum //是否保存到相册
			//correctOrientation //设置摄像机拍摄的图像是否为正确的方向
			var options = {
				quality: 50,
				destinationType: Camera.DestinationType.DATA_URL,
				sourceType: Camera.PictureSourceType.CAMERA,
				allowEdit: true,
				encodingType: Camera.EncodingType.PNG,
				targetWidth: 1000,
				targetHeight: 1000,
				popoverOptions: CameraPopoverOptions,
				saveToPhotoAlbum: true,
				correctOrientation: true　　
			};　　
			navigator.camera.getPicture(function(imageData) {
				if(callback)
					callback("data:image/jpeg;base64," + imageData);
			}, function(err) {
				if(error)
					error(err.toString());
			}, options);
		}

		//相册
		function takeLibrary(callback, error) {
			//maximumImagesCount 最大选择图片数量 最大15
			//width 筛选宽度：如果宽度为0，返回所有尺寸的图片
			//height 筛选高度：如果高度为0，返回所有尺寸的图片
			//quality 图像质量的大小，默认为100
			var options = {
				maximumImagesCount: 1,
				width: 1000,
				height: 1000,
				quality: 80
			};
			window.imagePicker.getPictures(function(results) {
				dataURItoBase64(results[0], function(data) {
					if(callback)
						callback(data);
				});
			}, function(err) {
				if(error)
					error(err.toString());
			}, options);
		}

		//保存图片到相册
		function saveImageToPhone(url, success, error) {
			var img = new Image();
			img.src = url;
			img.onload = function() {
				var canvas = document.createElement('canvas');
				canvas.width = img.width;
				canvas.height = img.height;
				var context = canvas.getContext('2d');
				context.drawImage(img, 0, 0);
				//执行保存
				var imageDataUrl = canvas.toDataURL('image/jpeg', 1.0);
				var imageData = imageDataUrl.replace(/data:image\/jpeg;base64,/, '');
				//执行保存
				cordova.exec(
					function() {
						//保存成功
						GoDialog.toast("图片保存成功");
						if(success)
							success();
					},
					function() {
						//保存失败
						GoDialog.toast("图片保存失败");
						if(error)
							error();
					},
					'Canvas2ImagePlugin',
					'saveImageDataToLibrary', [imageData]
				);
			};
		}

		return {
			//压缩文件
			compress: function(file, source_img_obj, quality, callback) {
				//获取照片方向角属性，用户旋转控制 
				EXIF.getData(file, function() {
					EXIF.getAllTags(this);
					var Orientation = EXIF.getTag(this, 'Orientation');
					var setObj = new Object(); //压缩参数
					setObj.width = 600; //宽度默认600
					setObj.quality = 0.7; //质量0.7
					file_compress2(source_img_obj, setObj, Orientation, function(base64, blobUrl, blob) {
						if(callback)
							callback(base64);
					});
				});
			},
			//文件上传
			upload: function(callback) {
				return file_upload(callback);
			},
			//原生图片选择
			imageNative: function(callback, error) {
				var buttons = new Array();
				buttons.push({
					text: '拍照',
					style: ''
				});
				buttons.push({
					text: '相册',
					style: ''
				});
				GoDialog.sheet('选择图片方式', '取消', buttons, function(index) {
					//拍照
					if(index == 0) {
						takePhone(callback, error);
					}
					//相册
					else if(index == 1) {
						takeLibrary(callback, error);
					}
				});
			},
			//图片保存到app
			imageSaveNative: function(photoPath, success, error) {
				//使用极光推送插件
				if(window.cordova && window.cordova.plugins) {
					saveImageToPhone(photoPath, success, error);
				} else {

				}
			}
		};
	})

	//区域关联
	libs.service("GoRegion", function(Http, GoDialog) {

		function buildInitRelativeData(initdata) {
			var data = {
				list1: [],
				value1: '',
				value1_select:{id:0,text:"请选择省份"},
				list2: [],
				value2: '',
				value2_select:{id:0,text:"请选择城市"},
				list3: [],
				value3: '',
				value3_select:{id:0,text:"请选择地区"}
			}

			var initData = initdata || [];
			for(var i = 0; i < 3 && i < initData.length; i++) {
				var l = initData[i].list || [];
				var v = initData[i].value || '';
				for(var j = 0; j < l.length; j++) {
					data['list' + (i + 1)].push({
						id: l[j][0],
						text: l[j][1]
					})
				}
				data['value' + (i + 1)] = v;
			}

			return data;
		}

		return {

			//
			// region: 【package:region_path_name:region_id】
			// 			或者：【region_id】
			// 			非必须
			// callback: function(success, data/errmsg)
			// 			success=true: data:三级联动数据域
			// 				data: {
			// 					list1: [{id: 'id', text: 'text'}, ...], value1: '',
			// 					list2: [...], value2: '',
			// 					list3: [...], value3: ''
			// 				}
			// 			success=false: errmsg
			//

			init: function(region, callback, error, done) {

				if(typeof callback != 'function') return;

				var param = {
					method: 'region.info.init',
					region_value: region
				}

				//post请求
				Http.post(param, function(res) {
					if(res.success == true) {
						callback(true, buildInitRelativeData(res.result.data), res.result.package);
					} else {
						GoDialog.toast(res.msg);
						callback(false, res.msg);
					}
				}, error, done);
			},

			//
			// region_id: 地域id
			// lvl: 联动层级:1,2,3
			// data: 三级联动数据域，参考init中数据结构
			// callback: function(success, list/errmsg)
			// 			success=true: list:子地域列表(结构参照接口文档)
			// 			success=false: errmsg
			//
			get_nextlvl: function(region_id, lvl, data, callback, error, done) {

				data.list3 = [], data.value3 = '';
				if(lvl == 1) {
					data.list2 = [], data.value2 = '';
				}

				if(!region_id) {
					callback && callback(true);
					return;
				}

				var param = {
					method: 'region.info.getNextLvl',
					region_id: region_id
				}

				//post请求
				Http.post(param, function(res) {
					if(res.success == true) {
						var list = res.result.list || [];

						for(var i = 0; i < list.length; i++) {
							data['list' + (lvl + 1)].push({
								id: list[i][0],
								text: list[i][1]
							})
						}

						callback && callback(true);
					} else {
						GoDialog.toast(res.msg);
						callback && callback(false, res.msg);
					}
				}, error, done);
			}
		}
	})

	//品牌分类
	libs.service("GoBrandCat", function(Http, GoDialog, $http) {

		function buildInitRelativeData(initdata) {
			var data = {
				list1: [],
				value1: '',
				value1_select:{id:0,text:"请选择省份"},
				list2: [],
				value2: '',
				value2_select:{id:0,text:"请选择城市"},
				list3: [],
				value3: '',
				value3_select:{id:0,text:"请选择地区"},
				list4: [],
				value4: '',
				list5: [],
				value5: ''
			}

			var initData = initdata || [];
			for(var i = 0; i < 5 && i < initData.length; i++) {
				var l = initData[i].list || [];
				var v = initData[i].value || '';
				for(var j = 0; j < l.length; j++) {
					data['list' + (i + 1)].push({
						id: l[j][0],
						text: l[j][1]
					})
				}
				data['value' + (i + 1)] = v;
			}

			return data;
		}

		return {

			/**
			 * param: {
			 * 			inputdata: 数组；每个元素的参数格式：cat_id,cat_id|brand_id|store_id，对应多组[品牌/分类]
			 *      	// brand_id:品牌id，存在时，根据品牌下的分类，筛选输出结果
			 *      	// store_id:商户id，同上
			 *
			 * 			with_brand: '1'
			 * 			// =1时:返回值包含品牌列表
			 * callback: function(success, data/errmsg, brandlist)
			 * 			success=true: data:三级联动数据域
			 *          data: [
			 * 			  // 第一个品牌
			 *            {
			 *              brand_id:
			 *              store_id:
			 *              cats: [ //该品牌下的分类集合
			 * 				  // 该品牌下的第一个分类
			 *                {
			 *                  // 第一级分类
			 * 					list1: [{id: 'id', text: 'text'}, ...], value1: '',
			 * 					// 第二级分类
			 * 					list2: [...], value2: '',
			 * 					...
			 *                },
			 * 				  // 该品牌下的第n个分类
			 *                ...
			 *              ],
			 *            },
			 * 			  // 第n个品牌
			 *            ...
			 *          ],
			 *          brand_list: [   参数with_brand == '1'时，有返回值
			 *              {brand_id=>'brand_id', store_id=>'store_id', brand_name=>'brand_name'},
			 *              ...
			 *          ]
			 * 			success=false: errmsg
			 * 			with_brand=1时候：返回brandlist（品牌列表）
			 */
			init: function(param, callback, error, done) {

				if(typeof callback != 'function') return;

				var postparam = {
					method: 'brand.info.initcat'
				}

				param.inputdata && (postparam['inputdata'] = param.inputdata);
				param.with_brand && (postparam['with_brand'] = param.with_brand);

				//post请求
				Http.post(postparam, function(res) {
					if(res.success == true) {
						var cd = [];

						var data = res.result.data;
						for(var i = 0; i < data.length; i++) {
							var brandStoreCats = data[i];

							var arrCatsPath = [];
							for(var j = 0; j < brandStoreCats['cats'].length; j++) {
								var cat_path = brandStoreCats['cats'][j];
								arrCatsPath.push(buildInitRelativeData(cat_path));
							}

							cd.push({
								brand_id: brandStoreCats['brand_id'],
								store_id: brandStoreCats['store_id'],
								cats: arrCatsPath,
							})
						}

						callback(true, cd, res.result.brand_list);
					} else {
						GoDialog.toast(res.msg);
						callback(false, res.msg);
					}
				}, error, done);
			},

			/**
			 * param: {cat_id: '分类id', store_id: '企业id', brand_id: '品牌id'}
			 *  param.store_id与param.brand_id：用以确认品牌所指定的分类，以此为筛选条件，过滤返回的分类集合。
			 * lvl: 变动层级:1,2,3,4
			 * data: 子数据域，参考init中数据结构
			 * callback: function(success, list/errmsg)
			 * 			success=true: list:子分类列表(结构参照接口文档)
			 * 			success=false: errmsg
			 */
			get_nextlvl: function(param, lvl, data, callback, error, done) {

				for(var i = lvl + 1; i <= 5; i++) {
					data['list' + i] = [], data['value' + i] = '';
				}

				if(!param || !param.cat_id) {
					try {
						callback && callback(true);
					} catch(ex) {

					} finally {
						done && done();
					}
					return;
				}

				var param = {
					method: 'brand.info.getNextCatLvl',
					cat_id: param.cat_id,
					store_id: param.store_id,
					brand_id: param.brand_id
				}

				//post请求
				Http.post(param, function(res) {
					if(res.success == true) {
						var list = res.result.list || [];

						for(var i = 0; i < list.length; i++) {
							data['list' + (lvl + 1)].push({
								id: list[i][0],
								text: list[i][1]
							})
						}

						callback && callback(true);
					} else {
						GoDialog.toast(res.msg);
						callback && callback(false, res.msg);
					}
				}, error, done);
			}
		}

	})

	//身份检查
	libs.service("GoCheck", function() {

		//验证身份证号方法
		function testID(idcard) {
			var Errors = new Array("true", "身份证号码位数不对!", "身份证号码出生日期超出范围或含有非法字符!", "身份证号码校验错误!", "身份证地区非法!");
			var area = {
				11: "北京",
				12: "天津",
				13: "河北",
				14: "山西",
				15: "内蒙古",
				21: "辽宁",
				22: "吉林",
				23: "黑龙江",
				31: "上海",
				32: "江苏",
				33: "浙江",
				34: "安徽",
				35: "福建",
				36: "江西",
				37: "山东",
				41: "河南",
				42: "湖北",
				43: "湖南",
				44: "广东",
				45: "广西",
				46: "海南",
				50: "重庆",
				51: "四川",
				52: "贵州",
				53: "云南",
				54: "西藏",
				61: "陕西",
				62: "甘肃",
				63: "青海",
				64: "宁夏",
				65: "xinjiang",
				71: "台湾",
				81: "香港",
				82: "澳门",
				91: "国外"
			}
			var idcard, Y, JYM;
			var S, M;
			var ereg;
			var idcard_array = new Array();
			idcard_array = idcard.split("");
			if(area[parseInt(idcard.substr(0, 2))] == null) return Errors[4];
			switch(idcard.length) {
				case 15:
					if((parseInt(idcard.substr(6, 2)) + 1900) % 4 == 0 || ((parseInt(idcard.substr(6, 2)) + 1900) % 100 == 0 && (parseInt(idcard.substr(6, 2)) + 1900) % 4 == 0)) {
						ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$/; //测试出生日期的合法性
					} else {
						ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$/; //测试出生日期的合法性
					}
					if(ereg.test(idcard))
						return Errors[0];
					else
						return Errors[2];
					break;
				case 18:
					if(parseInt(idcard.substr(6, 4)) % 4 == 0 || (parseInt(idcard.substr(6, 4)) % 100 == 0 && parseInt(idcard.substr(6, 4)) % 4 == 0)) {
						ereg = /^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$/; //闰年出生日期的合法性正则表达式
					} else {
						ereg = /^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$/; //平年出生日期的合法性正则表达式
					}
					if(ereg.test(idcard)) {
						S = (parseInt(idcard_array[0]) + parseInt(idcard_array[10])) * 7 + (parseInt(idcard_array[1]) + parseInt(idcard_array[11])) * 9 + (parseInt(idcard_array[2]) + parseInt(idcard_array[12])) * 10 + (parseInt(idcard_array[3]) + parseInt(idcard_array[13])) * 5 + (parseInt(idcard_array[4]) + parseInt(idcard_array[14])) * 8 + (parseInt(idcard_array[5]) + parseInt(idcard_array[15])) * 4 + (parseInt(idcard_array[6]) + parseInt(idcard_array[16])) * 2 + parseInt(idcard_array[7]) * 1 + parseInt(idcard_array[8]) * 6 + parseInt(idcard_array[9]) * 3;
						Y = S % 11;
						M = "F";
						JYM = "10X98765432";
						M = JYM.substr(Y, 1);
						if(M == idcard_array[17])
							return Errors[0];
						else
							return Errors[3];
					} else
						return Errors[2];
					break;
				default:
					return Errors[1];
					break;
			}
		}

		return {
			checkAlphaAndNumber: function(value) {
				return(/^[A-Za-z0-9]+$/.test(value));
			},
			checkZhstr: function(value) {
				return(/^[\u4e00-\u9fa5a-zA-Z]+$/.test(value));
			},
			checkEmail: function(value) {
				return(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value));
			},
			checkTel: function(value) {
				return(/^\d{1,100}$/.test(value));
			},

			checkMobile: function(value) {
				return(/^0{0,1}(13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])[0-9]{8}$/.test(value));
			},

			checkNumber: function(value) {
				return(/^[0-9]+$/.test(value));
			},

			testID: function(value) {
				var errmsg = testID(value);
				return errmsg;
			}
		}
	})

	//百度地图
	libs.service("GoMap", function(GoDialog) {

		function checkBMap() {
			if(typeof BMap == 'undefined') {
				GoDialog.alert('地图系统载入异常', '请尝试在联网状态下，重新启动APP')
				return false;
			}

			return true;
		}

		return {
			/**
			 * 获取keyword的坐标
			 * container_id：画面容器的id，必须
			 * keyword：要查找坐标的地址关键字（比如：上海市浦东新区东方明珠电视塔）
			 * callback：function(point)  point:坐标，point.lng/point.lat
			 * 									不存在：定位失败
			 */
			get_location: function(container_id, keyword, callback) {

				if(!checkBMap()) {
					callback && callback();
					return;
				}

				try {
					var map = new BMap.Map(container_id);
					var localSearch = new BMap.LocalSearch(map);
					localSearch.enableAutoViewport();

					localSearch.setSearchCompleteCallback(function(searchResult) {
						var poi = searchResult.getPoi(0);
						if(!poi || !poi.point || !poi.point.lng || !poi.point.lat) {
							callback && callback();
						} else {
							callback && callback(poi.point);
						}
					});
					localSearch.search(keyword);
				} catch(ex) {
					callback && callback();
				}
			},

			/**
			 * 向容器内设置设置地图坐标点
			 * container_id：画面容器的id
			 * pointsInfo：[
			 * 				{
			 * 					lng: xxx, lat: xxx,	//坐标
			 * 					content: 'xxxxx',	//坐标关键字
			 * 					其他
			 *				},
			 *				...
			 * 				]
			 * option：参考相关百度文档
			 * {
			 *     Dragging: boolean,
			 *     ScrollWheelZoom: boolean,
			 *     DoubleClickZoom: boolean,
			 *     Keyboard: boolean,
			 *     InertialDragging: boolean,
			 *     ContinuousZoom: boolean,
			 *     PinchToZoom: boolean,
			 *
			 *     fnClickPoint: 点击坐标后的回调，参数是pointsInfo中对应的数据
			 * }
			 */
			set_location: function(container_id, pointsInfo, option) {

				if(!checkBMap()) {
					return;
				}

				option = option || {};
				pointsInfo = pointsInfo || [];

				var map = new BMap.Map(container_id);

				// map.addControl(new BMap.NavigationControl());
				map.addControl(new BMap.ScaleControl());
				// map.addControl(new BMap.OverviewMapControl());

				if(option.Dragging === true) map.enableDragging();
				if(option.Dragging === false) map.disableDragging();

				if(option.ScrollWheelZoom === true) map.enableScrollWheelZoom();
				if(option.ScrollWheelZoom === false) map.disableScrollWheelZoom();

				if(option.DoubleClickZoom === true) map.enableDoubleClickZoom();
				if(option.DoubleClickZoom === false) map.disableDoubleClickZoom();

				if(option.Keyboard === true) map.enableKeyboard();
				if(option.Keyboard === false) map.disableKeyboard();

				if(option.InertialDragging === true) map.enableInertialDragging();
				if(option.InertialDragging === false) map.disableInertialDragging();

				if(option.ContinuousZoom === true) map.enableContinuousZoom();
				if(option.ContinuousZoom === false) map.disableContinuousZoom();

				if(option.PinchToZoom === true) map.enablePinchToZoom();
				if(option.PinchToZoom === false) map.disablePinchToZoom();

				map.clearOverlays(); //清空原来的标注

				var fnClickPoint = option.fnClickPoint;
				var isFirst = true;
				var hasNoFlag = false;
				var points = [];

				for(var i = 0; i < pointsInfo.length; i++) {
					var pi = pointsInfo[i];
					if(!pi || !pi.lng || !pi.lat) continue;

					var point = new BMap.Point(pi.lng, pi.lat);
					points.push(point);
					if(isFirst) {
						isFirst = false;
						map.centerAndZoom(point, 15);
					}

					if(pi.no_flag !== true) {
						var marker = new BMap.Marker(point);
						map.addOverlay(marker);

						if(typeof fnClickPoint == 'function') {
							marker.addEventListener("click", function(pi) { //给标注添加点击事件
								// this.openInfoWindow(infoWindow);
								fnClickPoint(pi);
							}.bind(marker, pi));
						}

						if(pi.content) {
							var label = new BMap.Label(pi.content, {
								offset: new BMap.Size(20, -10)
							});
							marker.setLabel(label);
						}
					} else {
						hasNoFlag = true;
					}
				}

				if(hasNoFlag == false && points.length > 1) {
					map.setViewport(points);
				}
			},

			//定位
			get_currentlocation: function(callback, cbLocaladdress) {

				if(!checkBMap()) {
					callback && callback();
					return;
				}

				if(window.cordova && window.cordova.plugins) {
					if(ionic.Platform.isIOS()) {
						//IOS定位
						navigator.geolocation.getCurrentPosition(function(position) {
							//获取定位
							var point = new BMap.Point(position.coords.longitude, position.coords.latitude);
							//原始坐标转换百度坐标
							var convertor = new BMap.Convertor();
							convertor.translate([point], 1, 5, function(data) {
								if(data.status === 0) {
									//返回百度坐标
									callback && callback(data.points[0])
									//逆编码
									if(cbLocaladdress) {
										var geoc = new BMap.Geocoder();
										geoc.getLocation(point, function(rs) {
											cbLocaladdress && cbLocaladdress(rs);
										});
									}
								}
							})
						});
					} else {
						// android是百度定位
						window.baidu_location.getCurrentPosition(function(position) {
							//获取定位
							var point = new BMap.Point(position.longitude, position.latitude);
							//返回百度坐标
							callback && callback(point)
							//逆编码
							if(cbLocaladdress) {
								var geoc = new BMap.Geocoder();
								geoc.getLocation(point, function(rs) {
									cbLocaladdress && cbLocaladdress(rs);
								});
							}
						});
					}
				} else {
					var geolocation = new BMap.Geolocation();
					geolocation.getCurrentPosition(function(result) {
						if(this.getStatus() == BMAP_STATUS_SUCCESS) {
							callback && callback(result.point)
							if(cbLocaladdress) {
								var geoc = new BMap.Geocoder();
								geoc.getLocation(result.point, function(rs) {
									cbLocaladdress && cbLocaladdress(rs);
								});
							}
						}
					});
				}
			},
			//保存内部坐标
			set_homelocaltion: function(params) {
				localStorage.setItem('longitude', params.longitude);
				localStorage.setItem('latitude', params.latitude);
			},
			//获取内部坐标
			get_homelocaltion: function(name) {
				return localStorage.getItem(name);
			},
			//获取内部坐标
			clear_homelocaltion: function() {
				localStorage.removeItem('longitude');
				localStorage.removeItem('latitude');
			}
		}
	})

	//聊天长连接
	libs.service("GoChat", function() {

		//创建长连接需要的用户信息
		var UserInfo = {
			//连接URL（固定的）
			dispathURL: '',
			//用户ID
			userid: 0,
			//LoginCode
			logincode: ''
		};

		return {
			//初始化长连接
			openConnect: function(url, userid, logincode) {
				//初始化用户信息
				UserInfo.userid = userid;
				UserInfo.logincode = logincode;
				UserInfo.dispathURL = url;
				//				console.log(UserInfo);
				//开启连接
				WebRTCConnect(UserInfo);
			},
			//获取聊天内容
			getChatMsg: function(callback, $scope) {
				initListenMsg(callback, $scope);
			},
			//关闭长连接
			closeConnect: function() {
				//关闭连接
				CloseWebRTCSocket();
			}
		}
	});

	//极光推送
	libs.service("GoPush", function(Http, GoPage, GoDialog) {

		//极光注册ID提交服务器
		function regist_push_id(registrationID) {
			try {
				var source = ionic.Platform.isIOS() ? "ios" : (ionic.Platform.isAndroid() ? "android" : null);
			} catch(ex) {
				var source = "";
			}

			if(!source) {
				return;
			}

			Http.post({
				"method": "member.registpush",
				"registration_id": registrationID,
				"source": source,
			}, function(result) {
				// if(result.status == 1) {
				// 	if(callOK)
				// 		callOK(result.info);
				// } else {
				// 	if(callFail)
				// 		callFail();
				// }
			});
		}

		return {
			//初始化
			init: function() {
				//使用极光推送插件
				if(window.cordova && window.cordova.plugins) {
					//启动极光推送服务 
					window.plugins.jPushPlugin.init();
					window.plugins.jPushPlugin.setDebugMode(false);
					window.plugins.jPushPlugin.requestPermission();
					window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);
				}
			},
			//注册提交
			regist: function() {
				if(window.cordova && window.cordova.plugins) {
					//注册设备
					window.plugins.jPushPlugin.getRegistrationID(function(registrationID) {
						regist_push_id(registrationID);
					});
				}
			},
			//收到通知时会触发该事件
			receiveNotification: function() {
				if(window.cordova && window.cordova.plugins) {
					//注册通知 只能注册一次
					document.addEventListener("jpush.receiveNotification", function(event) {
						window.plugins.jPushPlugin.setBadge(0);
						window.plugins.jPushPlugin.resetBadge();
						window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);
						//推送参数
						var type = 0;
						var pushid = 0;
						var kind = 0;
						var goodsid = 0;
						//区分ios和android
						var alertContent
						if(device.platform == "Android") {
							alertContent = event.alert
							//接收参数
							type = event.extras.type; //推送类型
							pushid = event.extras.pushid; //对应id
							kind = event.extras.kind; //活动类型
						} else {
							alertContent = event.aps.alert
							//接收参数
							type = event.type;
							pushid = event.pushid;
							kind = event.kind;
						}
						//消息提示
						GoDialog.confirm("提示", alertContent, function() {
							//是否打开跳转
							GoPage.go_push(type, pushid, kind);
						});
					}, false);
				}
			},
			//点击通知进入应用程序时会出发改事件
			openNotification: function() {
				if(window.cordova && window.cordova.plugins) {
					//注册通知 只能注册一次
					document.addEventListener("jpush.openNotification", function(event) {
						window.plugins.jPushPlugin.setBadge(0);
						window.plugins.jPushPlugin.resetBadge();
						window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);
						//推送参数
						var type = 0;
						var pushid = 0;
						var kind = 0;
						var goodsid = 0;
						//区分ios和android
						var alertContent
						if(device.platform == "Android") {
							alertContent = event.alert
							//接收参数
							type = event.extras.type;
							pushid = event.extras.pushid;
							kind = event.extras.kind;
						} else {
							alertContent = event.aps.alert
							//接收参数
							type = event.type;
							pushid = event.pushid;
							kind = event.kind;
						}
						//是否打开跳转
						GoPage.go_push(type, pushid, kind);
					}, false);
				}
			}
		}
	})

	//代码热更新
	libs.service("GoHotCode", function($timeout, GoDialog) {

		//准备更新
		function chcp_updateIsReadyToInstall() {
			//准备更新
			GoDialog.confirm("提示", "有版本更新，确定要更新吗?", function() {
				//执行安装
				chcp.installUpdate();
			});
		}
		//版本更新失败
		function chcp_updateLoadFailed() {
			GoDialog.alert("提示", "版本更新失败!");
		}
		//已经是最新版本
		function chcp_nothingToUpdate() {
			if(localStorage.getItem("initchcp") == undefined) {
				GoDialog.alert("提示", "已经是最新版本!");
			}
			localStorage.removeItem('initchcp');
		}
		//版本更新前
		function chcp_beforeInstall() {
			GoDialog.loading(true, "正在升级，升级完毕应用将自动重启...");
		}
		//版本更新成功
		function chcp_updateInstalled() {
			GoDialog.loading(false, "正在升级，升级完毕应用将自动重启...");
			localStorage.removeItem('isstart');
		}
		//安装失败
		function chcp_updateInstallFailed() {
			GoDialog.alert("提示", "文件安装失败!");
		}
		//无文件安装
		function chcp_nothingToInstall() {
			GoDialog.alert("提示", "无文件安装,已经是最新版本!");
		}

		return {
			//用户检查更新
			initUpdate: function() {
				//用户提示更新
				if(window.cordova && window.cordova.plugins) {
					//准备更新
					document.addEventListener('chcp_updateIsReadyToInstall', chcp_updateIsReadyToInstall, false);
					//更新失败
					document.addEventListener('chcp_updateLoadFailed', chcp_updateLoadFailed, false);
					//无更新
					document.addEventListener('chcp_nothingToUpdate', chcp_nothingToUpdate, false);
					//版本更新前
					document.addEventListener('chcp_beforeInstall', chcp_beforeInstall, false);
					//版本更新成功
					document.addEventListener('chcp_updateInstalled', chcp_updateInstalled, false);
					//安装失败
					document.addEventListener('chcp_updateInstallFailed', chcp_updateInstallFailed, false);
					//无文件安装
					document.addEventListener('chcp_nothingToInstall', chcp_nothingToInstall, false);
					//初始化提示
					localStorage.setItem("initchcp", 1);
					//执行检查
					$timeout(function() {
						chcp.fetchUpdate();
					}, 300);
				}
			},
			//用户检查更新
			checkUpdate: function() {
				//用户提示更新
				if(window.cordova && window.cordova.plugins) {
					chcp.fetchUpdate();
				}
			}
		}
	})

	//文件上传下载
	libs.service("FileSystem", function(Http, GoDialog) {

		//base64转Blob
		function dataURLtoBlob(dataurl) {
			var arr = dataurl.split(','),
				mime = arr[0].match(/:(.*?);/)[1],
				bstr = atob(arr[1]),
				n = bstr.length,
				u8arr = new Uint8Array(n);
			while(n--) {
				u8arr[n] = bstr.charCodeAt(n);
			}
			return new Blob([u8arr], {
				type: mime
			});
		}
		//保存到本地  
		function saveFile(dirEntry, blob, filename, data, success, error) {
			//创建文件  
			dirEntry.getFile(filename, {
				create: true
			}, function(fileEntity) {
				fileEntity.createWriter(function(fileWriter) {
					fileWriter.onwriteend = function() {
						if(success)
							success(data);
					}
					fileWriter.onerror = function(err) {
						if(error)
							error(err.toString());
					}
					//写文件
					fileWriter.write(blob);
				});
			}, function(err) {
				if(error)
					error(err.toString());
			});
		}
		//循环读取操作
		function readRuntime(fs, filename, success, error) {
			var dirReader = fs.root.createReader();
			var entries = [];
			//返回fileEntity数组 
			var readEntries = function() {
				dirReader.readEntries(function(data) {
					if(!data.length) {
						var items = showEntries(entries.sort(), filename);
						if(success)
							success(items);
					} else {
						entries = entries.concat(showToArray(data));
						readEntries();
					}
				}, function(err) {
					if(error)
						error(err);
				});
			}
			readEntries();
		}
		//完成读取操作  
		function showEntries(entries, filename) {
			var items = new Array();
			if(filename != "") {
				for(var i = 0; i < entries.length; i++) {
					if(entries[i].name == filename) {
						var temp = entries[i];
						//Android路径需要解码
						if(ionic.Platform.isAndroid())
							temp.nativeURL = decodeURI(temp.nativeURL);
						items.push(temp);
					}
				}
			} else {
				for(var i = 0; i < entries.length; i++) {
					var temp = entries[i];
					//Android路径需要解码
					if(ionic.Platform.isAndroid())
						temp.nativeURL = decodeURI(temp.nativeURL);
					items.push(temp);
				}
			}
			//返回
			return items;
		}
		//完成删除操作  
		function doneEntries(entries, delfiles) {
			//全部删除
			if(delfiles == undefined || delfiles.length == 0) {
				for(var i = 0; i < entries.length; i++) {
					deleteEntries(entries[i].nativeURL);
				}
			} else {
				//指定删除
				for(var i = 0; i < delfiles.length; i++) {
					var fileName = delfiles[i];
					for(var j = 0; j < entries.length; j++) {
						if(fileName == entries[j].nativeURL) {
							deleteEntries(entries[j].nativeURL);
							break;
						}
					}
				}
			}
		}
		//删除文件操作
		function deleteEntries(filename) {
			window.resolveLocalFileSystemURL(filename, function(fileEntry) {
				fileEntry.remove(function() {
					console.log('delete success');
				}, function(err) {
					console.error('delete error' + err);
				}, function() {
					console.log('file not exist');
				});
			});
		}
		//转换
		function showToArray(list) {
			return Array.prototype.slice.call(list || [], 0);
		}

		return {
			//文件上传(读取沙盒目录下的某目录文件,不存在直接创建)
			uploadFile: function(filename, order_id, act_type, success, error) {
				//这是app的写法
				if(window.cordova && window.cordova.plugins) {
					//创建文件  
					window.requestFileSystem(LocalFileSystem.PERSISTENT, 1024 * 1024, function(fs) {
						fs.root.getFile(filename, {
							create: false,
							exclusive: false
						}, function(fileEntity) {
							//读取文件
							fileEntity.file(function(files) {
								var reader = new FileReader();
								reader.onload = function() {
									//post请求
									var params = new Object();
									params.method = 'marketing.giving.upload';
									params.file = this.result;
									params.file_name = filename;
									params.order_id = order_id;
									params.act_type = act_type;
									Http.post(params, function(data) {
										if(success)
											success(data);
									});
								}
								reader.readAsDataURL(files);
							}, function(err) {
								if(error)
									error(err.toString());
							});
						});
					});
				} else {
					//这是web的写法
				}
			},
			//文件下载(写入沙盒目录下的某目录文件,不存在直接创建)
			downloadFile: function(file_id, success, error) {
				//这是app的写法
				if(window.cordova && window.cordova.plugins) {
					window.requestFileSystem(window.PERSISTENT, 5 * 1024 * 1024, function(fs) {
						//post请求
						var params = new Object();
						params.method = 'marketing.giving.down';
						params.file_id = file_id;
						Http.post(params, function(data) {
							if(data.result == null) {
								GoDialog.alert('提示', '下载失败');
							} else {
								//转换数据
								var blob = dataURLtoBlob(data.result.files);
								//保存文件
								saveFile(fs.root, blob, file_id + "_" + data.result.filename, data,
									function(result) {
										if(success)
											success(result);
									},
									function(err) {
										if(error)
											error(err);
									});
							}
						});
					}, function(err) {
						if(error)
							error(err);
					});
				} else {
					//这是web的写法
				}
			},
			//沙盒目录内容(读取沙盒目录下的某目录文件,不存在直接创建)
			readFileSystemRoot: function(file_id, success, error) {
				//这是app的写法
				if(window.cordova && window.cordova.plugins) {
					//显示根目录内容  
					window.requestFileSystem(LocalFileSystem.PERSISTENT, 1024 * 1024, function(fs) {
						//文件读取
						if(file_id == 0) {
							//读取所有文件
							readRuntime(fs, "",
								function(result) {
									if(success)
										success(result);
								},
								function(err) {
									if(error)
										error(err);
								});
						} else {
							//post请求
							var param = new Object();
							param.method = 'marketing.giving.down';
							param.file_id = file_id;
							Http.post(param, function(data) {
								if(data.result != null) {
									//读取指定类型文件
									readRuntime(fs, file_id + "_" + data.result.filename,
										function(result) {
											if(success)
												success(result);
										},
										function(err) {
											if(error)
												error(err);
										});
								}
							});
						}
					});
				} else {
					//这是web的写法
				}
			},
			//沙盒目录内容删除所有文件
			deleteFileSystemRoot: function(delfiles, success, error) {
				//这是app的写法
				if(window.cordova && window.cordova.plugins) {
					//显示根目录内容  
					window.requestFileSystem(LocalFileSystem.PERSISTENT, 1024 * 1024, function(fs) {
						//读取所有文件列表
						readRuntime(fs, file_id + "_" + data.result.filename,
							function(result) {
								doneEntries(result, delfiles);
								if(success)
									success();
							},
							function(err) {
								if(error)
									error(err);
							});
					});
				} else {
					//这是web的写法
				}
			},
			//打开文件(读取沙盒目录下的某目录文件,不存在直接创建)
			fileOpenWithDialog: function(fileURL, file_type, success, error) {
				//这是app的写法
				if(window.cordova && window.cordova.plugins) {
					cordova.plugins.fileOpener2.showOpenWithDialog(fileURL, file_type, function() {
						if(success)
							success();
					}, function(err) {
						if(error)
							error(err.toString());
					});
				} else {
					//这是web的写法
				}
			}
		}
	});

	//微信网页端登录
	libs.service("GoWapAuth", function($rootScope, $state, $stateParams, Http, GoDialog, GoPage, Auth) {

		//登录授权(QQ)
		function qqlogin_base_url(state) {
			var redirect_uri = encodeURIComponent(window.location.href);
			var scope = "get_user_info";
			var url = "https://graph.qq.com/oauth2.0/authorize?client_id=" + QQ_APPID +
				"&redirect_uri=" + redirect_uri +
				"&response_type=code&scope=" + scope +
				"&state=" + state;
			return url;
		}
		//用户授权(微信公众号)
		function snsapi_userinfo_url(state) {
			var redirect_uri = encodeURIComponent(window.location.href);
			var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
				WX_CHATID + '&redirect_uri=' +
				redirect_uri + '&response_type=code&scope=snsapi_userinfo&state=' +
				state + '#wechat_redirect';
			return url;
		}
		//用户授权(微信开放平台)
		function snsapi_scan_url(state) {
			var redirect_uri = encodeURIComponent(window.location.href);
			var scope = "snsapi_login";
			var url = "https://open.weixin.qq.com/connect/qrconnect?appid=" + WX_APPID +
				"&redirect_uri=" + redirect_uri +
				"&response_type=code&scope=" + scope +
				"&state=" + state + "#wechat_redirect";
			return url;
		}
		//微信内置浏览器
		function isWeiXin() {
			var ua = window.navigator.userAgent.toLowerCase();
			if(ua.match(/MicroMessenger/i) == 'micromessenger') {
				return true;
			} else {
				return false;
			}
		}

		//获取get参数
		function getParams(name) {
			var vars = new Object();　
			var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');　　
			for(var i = 0; i < hashes.length; i++) {
				var done = hashes[i].split('#');
				if(done.length > 1) {
					var hash = done[0].split('=');　　　　　　
					vars[hash[0]] = hash[1];　　
				} else {
					var hash = hashes[i].split('=');　　　　　　
					vars[hash[0]] = hash[1];　　
				}

			}
			return vars[name];
		};
		//用户登录(微信公众号)
		function user_login_wx(state, code) {
			var sourceStr = "";
			if(ionic.Platform.isIOS()) {
				sourceStr = "ios";
			} else {
				sourceStr = "android";
			}
			var param = new Object();
			param.method = 'member.thirdpartlogin';
			param.id = code;
			param.type = state;
			param.source = sourceStr;
			//post请求 检查用户是否存在,存在直接可以登录
			Http.post(param, function(res) {
				if(!res.success) {
					GoDialog.toast(res.msg);
					return;
				}
				//用户不再登录的时候使用
				localStorage.setItem("wx_openid", res.result.openid);
				wxinit(); //微信jssdk初始化
				//用户不存在,跳转用户绑定+注册
				if(res.result.islogin != undefined && !res.result.islogin ) {
					//用户点击微信登录时，才进入微信信任登录画面
					if(state=='loginwx'){
						//授权注册//过度使用
						sessionStorage.setItem("auth-headimgurl", res.result.userinfo.headimgurl);
						sessionStorage.setItem("auth-nickname", res.result.userinfo.nickname);
						GoPage.go_states("t-login-auth", {
							'uuid': res.result.unionid,
							'type': 'wx'
						});
					}
					return;
				} else {
					//保存用户信息
					saveBindInfo(res.result);
					return;
				}
			});
		}
		/**
		 * 根据授权code进行登录
		 */
		function setLoginCode(state, code) {
			var sourceStr = "";
			if(ionic.Platform.isIOS()) {
				sourceStr = "ios";
			} else {
				sourceStr = "android";
			}
			//可能有 bindwx wapbindwx wapbindqq qq wx
			var redirect_uri = encodeURIComponent(window.location.href);
			var param = new Object();
			param.method = 'member.thirdpartlogin';
			param.id = code;
			param.type = state;
			param.redirect_uri = redirect_uri;
			param.source = sourceStr;
			//post请求
			Http.post(param, function(res) {
				if(!res.success) {
					GoDialog.toast(res.msg);
					return;
				}
				//用户不存在-应该跳转
				if(res.result.islogin != undefined && !res.result.islogin) {
					//授权注册//过度使用
					sessionStorage.setItem("auth-headimgurl", state == "wapqq" ? res.result.userinfo.figureurl_qq_2 : res.result.userinfo.headimgurl);
					sessionStorage.setItem("auth-nickname", res.result.userinfo.nickname);
					GoPage.go_states("t-login-auth", {
						'uuid': res.result.unionid,
						'type': state == "wapqq" ? "qq" : "wx",
						'needVerifyCode':res.result.needVerifyCode
					});
					return;
				} else {
					//保存用户信息
					saveBindInfo(res.result);
					//恢复页面
					GoDialog.toast('登录成功');
					window.location.href = HTTP_SHARE_URL + "#/tab/center";
					return;
				}
			});
		}

		/**
		 * 根据授权code拿到
		 */
		function setCodeBind(type, code, url) {
			//可能有 bindwx wapbindwx wapbindqq qq wx
			var redirect_uri = encodeURIComponent(window.location.href);
			var params = {
				"id": code,
				"type": type,
				"redirect_uri": redirect_uri,
				"method": 'member.thirdpartbind'
			}
			//post请求
			Http.post(params, function(res) {
				if(!res.success) {
					GoDialog.toast(res.msg);
					return;
				}
				GoDialog.toast('绑定成功');
				window.location.href = HTTP_SHARE_URL + "#/tab/center";
			});
		}

		/**
		 * 用户信息保存
		 */
		function saveBindInfo(info) {
			for(var k in info) {
				if(info[k] == null || info[k] == undefined) {
					info[k] = '';
				}
			}
			//保存登录信息
			Auth.save_loginInfo(info);
		}

		// 生成签名
		function wx_sign(url, callback) {
			var params = {
				"method": 'member.thirdpartjsapiticket'
			}
			//post请求
			Http.post(params, function(res) {
				// 参数构成
				var ret = {
					jsapi_ticket: res.result.ticket,
					nonceStr: wx_noncestr(),
					timestamp: wx_timestamp(),
					url: url
				};
				// 签名做成
				var result = wx_raw(ret);
				ret.signature = Sha1.hash(result);
				ret.appid = res.result.appid;
				// 删除数据
				delete ret.jsapi_ticket;
				delete ret.url;
				// 函数回调
				callback(ret);
			});
		}

		// 生成签名的随机串
		function wx_noncestr() {
			return Math.random().toString(36).substr(2, 15);
		};
		// 生成签名的时间戳
		function wx_timestamp() {
			return parseInt(new Date().getTime() / 1000) + '';
		};
		// 排序整理数据
		function wx_raw(args) {
			var keys = Object.keys(args);
			keys = keys.sort();
			var newArgs = {};
			keys.forEach(function(key) {
				newArgs[key.toLowerCase()] = args[key];
			});
			var result = '';
			for(var k in newArgs) {
				if(newArgs.hasOwnProperty(k)) {
					result += '&' + k + '=' + newArgs[k];
				}
			}
			result = result.substr(1);
			return result;
		};
		//发起微信支付
		function wx_pay(result, callback, fail) {
			// 再执行自己的方法
			var config = {
				timestamp: result.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
				nonceStr: result.nonceStr, // 支付签名随机串，不长于 32 位
				package: result.prepay_id, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
				signType: result.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
				paySign: result.paySign, // 支付签名
				success: function(res) {
					if(callback) callback(res);
				},
				cancel: function() {
					if(fail) fail();
				}
			};
			// 调用微信js
			wx.chooseWXPay(config);
		};
		//微信发起扫一扫
		function wx_scan(callback, fail) {
			// 再执行自己的方法
			var config = {
				needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
				scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
				success: function(res) {
					if(callback)
						callback(res);
				},
				cancel: function() {
					if(fail)
						fail();
				}
			};
			// 调用微信js
			wx.scanQRCode(config);
		};
		//微信jssdk初始化
		function wxinit() {
			var that = this;
			var url = window.location.href.split('#')[0];
			//签名校验
			wx_sign(url, function(result) {
				// 配置参数
				var config = {
					debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
					appId: result.appid, // 必填，公众号的唯一标识
					timestamp: result.timestamp, // 必填，生成签名的时间戳
					nonceStr: result.nonceStr, // 必填，生成签名的随机串
					signature: result.signature, // 必填，签名，见附录1
					jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem',
						'showAllNonBaseMenuItem', 'translateVoice', 'startRecord', 'stopRecord', 'onRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'uploadVoice', 'downloadVoice',
						'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'closeWindow',
						'scanQRCode', 'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard'
					]
				}; // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
				// 通过config接口注入权限验证配置
				wx.config(config);
				// 通过ready接口处理成功验证
				wx.ready(function() {
					//已经准备完毕
					// config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，
					// 所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。
					// 对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
					$rootScope.init_tablocaltion();
				});
				// 通过error接口处理失败验证
				wx.error(function(res) {
					// config信息验证失败会执行error函数，如签名过期导致验证失败，
					// 具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
					$rootScope.init_tablocaltion();
				});
			});
		}

		return {
			//微信端
			isWeiXin: function() {
				return isWeiXin();
			},
			//微信公众号
			iswechat: function(callback, fail) {
				if(isWeiXin()) {
					if(callback)
						callback()
				} else {
					if(fail)
						fail()
				}
			},
			//初始化
			exec: function() {
				//授权code
				var code = getParams("code");
				var state = getParams("state");
				//进行QQ登录
				if(code != undefined && state == "wapqq") {
					setLoginCode(state, code);
				}
				//进行微信登录
				if(code != undefined && state == "wapwx") {
					setLoginCode(state, code);
				}
				//进行QQ绑定
				if(code != undefined && state == "wapbindqq") {
					setCodeBind("wapqq", code);
				}
				//进行微信绑定(开放平台)
				if(code != undefined && state == "wapbindwx") {
					setCodeBind("wapwx", code);
				}
			},
			//初始化
			execwx: function() {
				//1.读取用户,是否存在,不存在跳转微信授权
				//2.微信授权回调,获取用户登录code
				var code = getParams("code"); //微信授权code
				var state = getParams("state"); //微信授权状态
				var uid = Auth.get_user_id();
				var openwx_code = sessionStorage.getItem("openwx_code");
				//是否已经登录
				if(uid == '') {
					//开始登录 1.获取code 2.拿code换openid
					if(code == undefined) {
						//存入要回调的地址
						//默认静默授权
						setTimeout("javascript:location.href='" + snsapi_userinfo_url("openwx") + "'", 100);
						return;
					} else if(state == "openwx" && (openwx_code == undefined || openwx_code == null)) {
						//默认不自动跳转绑定 add by libaoji
						//授权回调(微信打开链接自动登录)
						user_login_wx(state, code);
						//存入code
						sessionStorage.setItem("openwx_code", code);
					} else if(state == "loginwx") {
						//授权回调 进行微信登录
						user_login_wx(state, code);
					} else if(state == "wapqq") {
						//授权回调 进行qq登录
						user_login_wx(state, code);
					}
				} else {
					if(state == "bindwx") {
						//授权回调 进行微信绑定
						setCodeBind("bindwx", code);
					}
					//进行QQ绑定
					if(state == "wapbindqq") {
						setCodeBind("wapqq", code);
					}
				}
				
			},
			//分享按钮开关
			execisoff: function(isoff) {
				//是否开启隐藏
				if(isoff) {
					//批量隐藏
					wx.hideMenuItems({
						// 要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮，所有menu项见附录3
						menuList: [
							'menuItem:share:appMessage',
							'menuItem:share:timeline',
							'menuItem:favorite',
							'menuItem:share:qq',
							'menuItem:share:QZone',
							'menuItem:share:weiboApp',
							'menuItem:openWithQQBrowser',
							'menuItem:copyUrl',
							'menuItem:openWithSafari'
						]
					});
				} else {
					//批量显示
					wx.showMenuItems({
						// 要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮，所有menu项见附录3
						menuList: [
							'menuItem:share:appMessage',
							'menuItem:share:timeline',
							'menuItem:favorite',
							'menuItem:share:qq',
							'menuItem:share:QZone',
							'menuItem:share:weiboApp',
							'menuItem:openWithQQBrowser',
							'menuItem:copyUrl',
							'menuItem:openWithSafari'
						]
					});
				}
			},
			//设定分享
			execshare: function(params) {

				var title = params.title == undefined ? "未来万家商城" : params.title;
				var desc = params.desc == undefined ? "不断完善标准、开拓创新、勇于超越，客户的满意是未来之星人永恒的追求。" : params.desc;
				var link = params.link == undefined ? HTTP_SHARE_URL + "index.html" : HTTP_SHARE_URL + "index.html#/tab/" + params.link;
				var imgUrl = params.thumb == undefined ? HTTP_SHARE_URL + "logo.png" : params.thumb;
				
				//获取“分享到朋友圈”按钮点击状态及自定义分享内容接口
				wx.onMenuShareTimeline({
					title: title,
					desc: desc,
					link: link,
					imgUrl: imgUrl,
					success: function() {
						// 用户确认分享后执行的回调函数
					},
					cancel: function() {
						// 用户取消分享后执行的回调函数
					}
				});

				//获取“分享给朋友”按钮点击状态及自定义分享内容接口
				wx.onMenuShareAppMessage({
					title: title,
					desc: desc,
					link: link,
					imgUrl: imgUrl,
					success: function(res) {
						// 用户确认分享后执行的回调函数
					},
					cancel: function(res) {
						// 用户取消分享后执行的回调函数
					}
				});

				//获取“分享到QQ”按钮点击状态及自定义分享内容接口
				wx.onMenuShareQQ({
					title: title,
					desc: desc,
					link: link,
					imgUrl: imgUrl,
					success: function() {
						// 用户确认分享后执行的回调函数
					},
					cancel: function() {
						// 用户取消分享后执行的回调函数
					}
				});

				//获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口
				wx.onMenuShareWeibo({
					title: title,
					desc: desc,
					link: link,
					imgUrl: imgUrl,
					success: function() {
						// 用户确认分享后执行的回调函数
					},
					cancel: function() {
						// 用户取消分享后执行的回调函数
					}
				});

				//获取“分享到QQ空间”按钮点击状态及自定义分享内容接口
				wx.onMenuShareQZone({
					title: title,
					desc: desc,
					link: link,
					imgUrl: imgUrl,
					success: function() {
						// 用户确认分享后执行的回调函数
					},
					cancel: function() {
						// 用户取消分享后执行的回调函数
					}
				});
			},
			//微信支付
			execpay: function(params, callback, fail) {
				//微信支付
				wx_pay(params, function() {
					if(callback)
						callback();
				}, function() {
					if(fail)
						fail();
				});
			},
			//QQ绑定
			bindQQ: function() {
				//请求QQ 获取Authorization Code
				//用户授权
				setTimeout("javascript:location.href='" + qqlogin_base_url("wapbindqq") + "'", 100);
			},
			//微信绑定
			bindWX: function() {
				//在微信浏览器内
				if(isWeiXin()) {
					//用户授权
					setTimeout("javascript:location.href='" + snsapi_userinfo_url("bindwx") + "'", 100);
				} else {
					//用户授权
					setTimeout("javascript:location.href='" + snsapi_scan_url("wapbindwx") + "'", 100);
				}
			},
			//QQ登录
			loginQQ: function() {
				//请求QQ 获取Authorization Code
				//用户授权
				setTimeout("javascript:location.href='" + qqlogin_base_url("wapqq") + "'", 100);
			},
			//微信登录
			loginWX: function() {
				if(isWeiXin()) {
					//用户授权
					setTimeout("javascript:location.href='" + snsapi_userinfo_url("loginwx") + "'", 100);
				} else {
					//用户授权
					setTimeout("javascript:location.href='" + snsapi_scan_url("wapwx") + "'", 100);
				}
			},
			//微信扫一扫
			scanWX: function(callback, fail) {
				wx_scan(function(result) {
					if(callback)
						callback(result);
				}, function() {
					if(fail)
						fail();
				});
			},
		};
	});

	//扫码机制
	libs.service("GoScan", function(GoDialog) {
		return {
			barcodeScanner: function(callback) {
				if(window.cordova && window.cordova.plugins) {
					var options = {
						preferFrontCamera: false, // iOS and Android
						showFlipCameraButton: false, // iOS and Android
						showTorchButton: true, // iOS and Android
						torchOn: true, // Android, launch with the torch switched on (if available)
						saveHistory: true, // Android, save scan history (default false)
						prompt: "请对准扫描框范围进行扫码", // Android
						resultDisplayDuration: 500, // Android, display scanned text for X ms. 0 suppresses it entirely, default 1500
						formats: "QR_CODE,PDF_417", // default: all but PDF_417 and RSS_EXPANDED
						orientation: "portrait", // Android only (portrait|landscape), default unset so it rotates with the device
						disableAnimations: true, // iOS
						disableSuccessBeep: true // iOS and Android
					};
					//扫码二维码
					cordova.plugins.barcodeScanner.scan(function(result) {
						if(callback)
							callback(result);
						//									alert("We got a barcode\n" +
						//										"Result: " + result.text + "\n" +
						//										"Format: " + result.format + "\n" +
						//										"Cancelled: " + result.cancelled);
					}, function(error) {
						GoDialog.alert("扫码失败!");
					}, options);
				}
			}
		};
	});

	return libs;
});